Explain Codes LogoExplain Codes Logo

How do I format a date in JavaScript?

javascript
date-formatting
locale-strings
date-extraction
Nikita BarsukovbyNikita Barsukov·Oct 6, 2024
TLDR

Use the toLocaleDateString():

const date = new Date().toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); console.log(date); // e.g., "Monday, April 3, 2023"

This function formats the date according to the given locale and option settings.

Diving deeper

Manipulating locale formats

toLocaleDateString can adapt to different locales. Simply change the locale string to format the date according to various international standarts:

const date = new Date(); console.log(date.toLocaleDateString('de-DE')); // German tastes console.log(date.toLocaleDateString('ja-JP')); // Japanese finesse

Piece-by-piece date extraction

Need just the day, month or year from a date? JavaScript provides easy methods:

let now = new Date(); console.log(now.getFullYear()); // Spock's log, Star Date... console.log(now.getMonth() + 1); // Months are like arrays, starting from 0 console.log(now.getDate()); // Day, a Solar System unit

Remember, increment the month by 1 - because getMonth() starts from 0, just like arrays.

Not just a date

Time is also crucial

toLocaleString formats the time in addition to the date:

let dateTimeOptions = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true }; console.log(new Date().toLocaleString("en-US", dateTimeOptions)); // Complete datetime

Timezone preservation

When dealing with timezones, convert to your local timezone before using toISOString().

const date = new Date(); const localDate = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)); console.log(localDate.toISOString()); // Local flavor preserved

Dealing with single digits

Ensure that day and month always appear as two digits by padding them with zeros:

const pad = n => n < 10 ? `0${n}` : n; console.log(`${pad(new Date().getMonth() + 1)}-${pad(new Date().getDate())}`);

Intricate formats with Intl.DateTimeFormat

Unlock real power with Intl.DateTimeFormat(). Its .formatToParts() method gives you granular control:

const date = new Date(); const formatter = new Intl.DateTimeFormat('en', { month: 'short', day: '2-digit', year: 'numeric' }); const parts = formatter.formatToParts(date); console.log(`${parts[2].value}-${parts[0].value}-${parts[4].value}`); // Doomsday's date

Libraries worth considering

Consider Luxon or date-fns as lightweight alternatives to Moment.js:

// date-fns example import { format } from 'date-fns'; console.log(format(new Date(), 'yyyy-MM-dd')); // ISO with style

Quick date formatting tricks

Some quick and dirty ways to format dates:

// Format as YYYY-MM-DD const isoDate = new Date().toISOString().slice(0, 10); console.log(isoDate); // Quick 'n' tidy