Explain Codes LogoExplain Codes Logo

How do I get the current date in JavaScript?

javascript
date-formatting
cross-browser
locale-specific
Anton ShumikhinbyAnton Shumikhin·Aug 18, 2024
TLDR

To access the current date in JavaScript, profound usage of new Date() instance is required:

let currentDate = new Date(); console.log(currentDate.toISOString());

Here, a Date object corresponding to now is created, and it's output in an ISO format. Further refining the display can be achieved through methods like .toISOString(), .toLocaleDateString(), and .toTimeString().

Date Formatting

Standard date format

The date in standard form (specifically YYYY-MM-DD) could be quickly achieved using the toISOString() and slice() methods (slicing the pizza of time anyone? 🍕):

let isoDate = new Date().toISOString().slice(0, 10); console.log(isoDate);

Locale-specific date formatting

Need your date hand-tailored? Use .toLocaleDateString():

let localeDate = new Date().toLocaleDateString('en-US'); console.log(localeDate);

Need to further polish the format based on a locale? Customize the date with options like a pro tailor:

let options = { year: 'numeric', month: 'long', day: 'numeric' }; console.log(new Date().toLocaleDateString('en-US', options));

UTC and ISO-based Dates

To get an accurate snapshot of UTC timing, .toISOString() is your friend:

console.log(new Date().toISOString());

Time Adjustments and Cross-Browser Compatibility

Setting the time to midnight

Regardless of time zone, if you want your date to start at midnight (because who doesn't enjoy midnight snacks?), you can set the time to midnight:

let beginningOfDay = new Date(); beginningOfDay.setHours(0, 0, 0, 0); console.log(beginningOfDay);

Ensuring cross-browser compatibility

To ensure cross-browser compatibility (Google, Firefox, Safari- oh my!), adjust the format:

let crossBrowserDate = new Date().toISOString().slice(0, 10).replace(/-/g,'/'); console.log(crossBrowserDate);

Advanced Formatting with Libraries

For advanced formatting as unique as your coffee order, consider using an external library like Date.format.min.js or dateFormat.min.js:

// Using Date.format.min.js console.log(new Date().format('m/d/Y')); // Using dateFormat.min.js for PHP-like formatting console.log(dateFormat(new Date(), 'mmmm dS, yyyy'));

These libraries offer compound formats, constants, and more sophisticated pretty date formats (because who doesn't like pretty things?). They even allow for escaping characters in the format string, offering full customization (because sometimes escape is necessary):

console.log(new Date().format('m/d/Y \\a\\t h:i:s A'));

Working with Day and Month Names

Translating numbers to names

To translate month and day numbers to names, make arrays your accomplice. After all, "March" sounds better than "3":

// Array entries = secret code names for months and days let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; let monthName = months[today.getMonth()]; let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; let dayName = days[today.getDay()];

Master Punctuation

Are your dates losing their "st", "nd", "rd", "th" suffixes? Time for a rescue mission with domEnder:

// Suffixes reporting for duty, sir! function domEnder(day) { let suffix = ["th", "st", "nd", "rd"][(day % 10 > 3) ? 0 : (day % 100 - day % 10 != 10) * day % 10]; return day + suffix; }