How do I format a date in JavaScript?
Use the toLocaleDateString()
:
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:
Piece-by-piece date extraction
Need just the day, month or year from a date? JavaScript provides easy methods:
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:
Timezone preservation
When dealing with timezones, convert to your local timezone before using toISOString()
.
Dealing with single digits
Ensure that day and month always appear as two digits by padding them with zeros:
Intricate formats with Intl.DateTimeFormat
Unlock real power with Intl.DateTimeFormat()
. Its .formatToParts()
method gives you granular control:
Libraries worth considering
Consider Luxon or date-fns as lightweight alternatives to Moment.js:
Quick date formatting tricks
Some quick and dirty ways to format dates:
Was this article helpful?