Formatting A Date in JS Without A Library or with DayJS

Formatting A Date in JS Without A Library or with DayJS

Formatting a Date in JS Without A Library

Most of us who use momentjs and dayjs JavaScript don’t always notice that Javascript has a native Internationalization API that provides some date formatting methods. It is built in. There is no need for an external library.

Here is a Date object:

> const now = new Date();
> now
2020-04-21T18:25:38.902Z

We can use the default formatting with this API:

> Intl.DateTimeFormat('en-US').format(now)
"4/21/2020"

There are also other more advanced options. For example, the dateStyle option has four possible values full, long, medium and short:

> Intl.DateTimeFormat('en-US', { dateStyle: "full" }).format(now)
"Tuesday, April 21, 2020"
> Intl.DateTimeFormat('en-US', { dateStyle: "long" }).format(now)
"April 21, 2020"
> Intl.DateTimeFormat('en-US', { dateStyle: "medium" }).format(now)
"Apr 21, 2020
> Intl.DateTimeFormat('en-US', { dateStyle: "short" }).format(now)
"4/21/20"

Formatting a Date in JS with dayjs

With dayjs, a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times, you can do a similar formating with the object returned from the library.

> const now = dayjs();
> now.format('YYYY/MM/DD')
'2020/04/21'

However, to get localized formats, we need to bring in a plugin. You can then use a one of the localized formats:

> dayjs.extend(localizedFormat)
> const now = dayjs();
> now.format('L LT')
'04/21/2020 11:25 AM'
> now.format('LLLL')
'Tuesday, April 21, 2020 11:25 AM'
> now.format('LL')
'April 21, 2020'
> now.format('ll')
'Apr 21, 2020'
> now.format('L')
'04/21/2020'

For browsers, the localized string will be render for the user in the language that they are viewing the page.

Overall, I favor using dayjs because the library provides additional functionality. However, it important to keep in mind, for small codebases, the native Intl will usually do the trick.