Published on

Format Date and Time using Intl DateTimeFormat in Javascript

Authors

Intl is a new Javascript API which focused on Internationalization (i18n)

It is primarily used for handling formatting-related things depending on where you are from (location)

One of the interesting things about this API is that you can use it for timezone conversion. Here is how to do it.

And we'll be utilizing its DateTimeFormat

Formatting Date

You can customize the return date format by passing dateStyle property and depending on the local you pass the value format will change.

dateStyleLocale (en-US)Locale (en-IN)
fullFriday, March 17, 2023Friday, 17 March, 2023
longMarch 17, 202317 March 2023
mediumMar 17, 202317-Mar-2023
short3/17/2317/03/23
new Intl.DateTimeFormat("en-IN",{
    dateStyle:"full",
}).format(new Date()) // Friday, March 17, 2023

Formatting Time

Similarly, we can customize time as well by passing timeStyle property

timeStyleLocale (en-US)Locale (en-IN)
full1:10:10 PM Eastern Daylight Time1:13:41 pm Eastern Daylight Time
long1:10:29 PM EDT1:13:27 pm GMT-4
medium1:10:44 PM1:13:10 pm
short1:10 PM1:11 pm
new Intl.DateTimeFormat("en-US",{
    timeStyle:"short",
}).format(new Date()) // 1:10 PM

Formatted Date + Time

You can combine dateStyle and timeStyle properties as well.

Note: timeStyle can be used with dateStyle, but not with other options (e.g. weekday, hour, month, etc.).

new Intl.DateTimeFormat("en-US",{
    dateStyle:"short",
    timeStyle:"short",
}).format(new Date()) // 3/17/23, 10:55 PM

Formatting using a different timezone

You can pass in timeZone property to configure the timezone as per your needs

new Intl.DateTimeFormat("en-US",{
    timeZone:"America/New_York",
    dateStyle:"short",
    timeStyle:"short",
}).format(new Date()) // 3/17/23, 1:16 PM

Similarly, there are other options using which you can customize the date or time as per your needs. Learn more about it in the docs

Happy formatting dates!