Explain Codes LogoExplain Codes Logo

Getting current date and time in JavaScript

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex Kataev·Dec 14, 2024
TLDR

To immediately obtain the current date and time, leverage the Date object in JavaScript using new Date(). Here's the example:

const now = new Date(); console.log(now); // Bam! This outputs the current date and time.

For localized or ISO-standard outputs, employ methods like now.toLocaleString() or now.toISOString() for formatted string representation of the date.

Exploiting the get Methods

Methods such as now.getDate() and now.getMonth() can be invoked for granular control. The .getDate() method retrieves the day of the month, the .getMonth() method fetches the index of the month (add 1 to get the actual calendar month).

Mastering month indexing and formatting

Defeating the 0-indexed month trap

JavaScript has this quirky behavior where months begin counting from 0. So, to get the civilian month, add 1 to the result:

const month = now.getMonth() + 1; // Now, January is 1 and not 0. Surprise!

Leading the charge with leading zeros

When formatting, single-digit numbers might need leading zeros. This function tackles that with ease:

function padTo2Digits(num) { return num.toString().padStart(2, '0'); // Turns 9 into 09, but leaves 10 alone }

Making MySQL cozy with JavaScript

In circumstances requiring MySQL's datetime format, utilize this pragmatic function:

function toMySQLFormat(date) { /* Formats the date as "yyyy-mm-dd hh:mm:ss" - just how MySQL likes it! */ return date.getFullYear() + '-' + padTo2Digits(date.getMonth() + 1) + '-' + padTo2Digits(date.getDate()) + ' ' + padTo2Digits(date.getHours()) + ':' + padTo2Digits(date.getMinutes()) + ':' + padTo2Digits(date.getSeconds()); }

Developing the ticking clock

Here a setInterval() function is used to display a constantly updating clock:

setInterval(() => { /* Turns out watching a clock in JavaScript is also as fun as in real life Every second, updates the clock on the website */ document.getElementById('clock').innerText = new Date().toLocaleString(); }, 1000);

Increasing the power of Date objects with prototypes

Constructing Custom Methods

Applying the Date.prototype allows us to create methods all Date instances can use:

// 'today' method for Date instances, JS objects growing up so fast! Date.prototype.today = function() { return `${this.getFullYear()}-${padTo2Digits(this.getMonth() + 1)}-${padTo2Digits(this.getDate())}`; }; // 'timeNow' method for Date instances, as if they weren't stylish enough! Date.prototype.timeNow = function() { return `${padTo2Digits(this.getHours())}:${padTo2Bits(this.getMinutes())}:${padTo2Bits(this.getSeconds())}`; }; const now = new Date(); console.log(now.today()); // Outputs current date in YYYY-MM-DD format console.log(now.timeNow()); // Outputs current time as HH:MM:SS

Localizing and Customizing

The toLocaleDateString() and toLocaleTimeString() are methods are available for localized date and time formats, which can be customized to suit your application:

const options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }; console.log(now.toLocaleDateString('en-US', options)); // "The way Americans like it - April 21, 2023" console.log(now.toLocaleTimeString('en-US', options)); // "2:45:30 PM - Ready for Tea Time?"

Formatting without Comma Interruptions

If you want to keep those pesky commas at bay in the toLocaleString() output, this utility function does the job:

function toLocaleStringNoCommas(date) { return date.toLocaleString().replace(/,/g, ''); // Commas are so passé! }