Explain Codes LogoExplain Codes Logo

Where can I find documentation on formatting a date in JavaScript?

javascript
date-formatting
javascript-date
intl-datetimeformat
Alex KataevbyAlex Kataev·Sep 4, 2024
TLDR

To fast-track your way to date formatting in JavaScript, you can leverage the Date object's toLocaleDateString() for locale-specific display, or toISOString() for the standardized ISO format. For a more customized touch, Intl.DateTimeFormat is your buddy. Also, look no further than robust libraries such as moment.js or date-fns for comprehensive formatting options.

Let's format a date string as 'YYYY-MM-DD':

let today = new Date(); let formattedDate = `${today.getFullYear()}-${(today.getMonth()+1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`; // Output: 'YYYY-MM-DD' and no Y2K bug this time, folks!

And here's how you sprinkle some locale spice:

let formattedDate = new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }); // Output: 'e.g., December 17, 2020', 'Murican Style!

Fundamentals of JavaScript date methods

Setting off on your adventure with JavaScript's Date object, you need to equip yourself with some core mechanics, grappling with date conversion, manipulation and formatting. So, let's plunge in.

Intrinsic Date methods

Before sprinting to a third-party library, take a moment to appreciate JavaScript's native offerings. The Date object has nifty methods such as getDate(), getMonth(), and getFullYear(), which you can use to extract date components. Also, remember that getMonth() will have you thinking it's getSoonToBeMonth(), for January starts at zero so always increment by 1.

let date = new Date(); console.log(date.getMonth() + 1); // Prints correct month number, not a software bug, it's a feature!

Formatting with a localized touch

With the Intl.DateTimeFormat object, formatting dates respecting local conventions is as simple as pie. Go fancy with time zones, numbering systems, and many, many more:

let dateFormatter = new Intl.DateTimeFormat('en-GB', { dateStyle: 'full' }); console.log(dateFormatter.format(new Date())); // 'e.g., Thursday, 17 December 2020', Yeah! That's how British folks like it!

Custom-IS-more

Custom formatting might feel like you're paving your own road, room for a lot of ditches on the way right? That's where manual construction of the date string comes in. For starters, don't leave the single digits hanging, zero-pad them, it's definitely better than padding in a boxing match! What's more, while toISOString() is a life-saver for a universal standard, you might find it too constrictive or just plain verbose. Isn't speaking succinctly an art?

Playback warnings

The seemingly harmless toString() is a cunning method that can produce varying outputs, depending on which side of the browser bed it woke up. Thus, for consistent formatting, choose your explicit methods wisely. And oh boy, with ECMAScript 2020, Christmas came early with Date.prototype.toJSON() in the stocking, for a JSON-compatible date representation.

Power-play with libraries

The native Date object is indeed a powerhouse, but for the heavyweight date formatting needs, a library might be what pulls up your sleeves. Libraries such as moment.js not only bring simplicity to complex operations, but also ensure consistency across browsers and locales.

Library-rich formatting

Ever imagined a world with easy parsing, formatting, manipulating, and even querying dates? Well, moment.js is not shy to give it all. For the calorie-conscious coders, date-fns offers a modular serving of date utilities.

Locale-aware formatting

A library provides a safe shelter from those pesky DST changes or browser quirks with their locale implementations. They generally come equipped with simple APIs to pretty up your dates, locale-agnostic:

console.log(moment(new Date()).format('LL')); // 'December 17, 2020', because date should look good too, right? console.log(dateFns.format(new Date(), 'PPP')); // 'Dec 17th, 2020', because dates can sound chummy too!

Performance matters

Libraries might be the sweetest berries, but remember, they come at a size cost. Always be mindful to only import what you need, to keep the load light on your app, or look for minimal libs like day.js.