- Published on
Format Date and Time using Intl DateTimeFormat in Javascript
- Authors
- Name
- Ashik Nesin
- @AshikNesin
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.
dateStyle | Locale (en-US) | Locale (en-IN) |
---|---|---|
full | Friday, March 17, 2023 | Friday, 17 March, 2023 |
long | March 17, 2023 | 17 March 2023 |
medium | Mar 17, 2023 | 17-Mar-2023 |
short | 3/17/23 | 17/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
timeStyle | Locale (en-US) | Locale (en-IN) |
---|---|---|
full | 1:10:10 PM Eastern Daylight Time | 1:13:41 pm Eastern Daylight Time |
long | 1:10:29 PM EDT | 1:13:27 pm GMT-4 |
medium | 1:10:44 PM | 1:13:10 pm |
short | 1:10 PM | 1: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!