- Intl.DateTimeFormat
- Try it
- Constructor
- Static methods
- Instance properties
- Instance methods
- Examples
- Using DateTimeFormat
- Using locales
- Using options
- Specifications
- Browser compatibility
- See also
- How to Format a Date with JavaScript – Date Formatting in JS
- How to Use the JavaScript Date Object
- Basic JavaScript Date Formatting Methods
- Custom Date Formatting in JavaScript
- How to Handle Time Zones When Working with Dates
- Common Date Formatting Patterns
- How to Handle Date Input
- Wrapping Up
Intl.DateTimeFormat
The Intl.DateTimeFormat object enables language-sensitive date and time formatting.
Try it
Constructor
Creates a new Intl.DateTimeFormat object.
Static methods
Returns an array containing those of the provided locales that are supported without having to fall back to the runtime’s default locale.
Instance properties
These properties are defined on Intl.DateTimeFormat.prototype and shared by all Intl.DateTimeFormat instances.
The constructor function that created the instance object. For Intl.DateTimeFormat instances, the initial value is the Intl.DateTimeFormat constructor.
The initial value of the @@toStringTag property is the string «Intl.DateTimeFormat» . This property is used in Object.prototype.toString() .
Instance methods
Getter function that formats a date according to the locale and formatting options of this DateTimeFormat object.
This method receives two Dates and formats the date range in the most concise way based on the locale and options provided when instantiating DateTimeFormat .
This method receives two Dates and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range.
Returns an Array of objects representing the date string in parts that can be used for custom locale-aware formatting.
Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
Examples
Using DateTimeFormat
In basic use without specifying a locale, DateTimeFormat uses the default locale and default options.
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // toLocaleString without arguments depends on the implementation, // the default locale, and the default time zone console.log(new Intl.DateTimeFormat().format(date)); // "12/19/2012" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)
Using locales
This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // Results below use the time zone of America/Los_Angeles (UTC-0800, Pacific Standard Time) // US English uses month-day-year order console.log(new Intl.DateTimeFormat("en-US").format(date)); // "12/19/2012" // British English uses day-month-year order console.log(new Intl.DateTimeFormat("en-GB").format(date)); // "19/12/2012" // Korean uses year-month-day order console.log(new Intl.DateTimeFormat("ko-KR").format(date)); // "2012. 12. 19." // Arabic in most Arabic speaking countries uses real Arabic digits console.log(new Intl.DateTimeFormat("ar-EG").format(date)); // "١٩/١٢/٢٠١٢" // for Japanese, applications may want to use the Japanese calendar, // where 2012 was the year 24 of the Heisei era console.log(new Intl.DateTimeFormat("ja-JP-u-ca-japanese").format(date)); // "24/12/19" // when requesting a language that may not be supported, such as // Balinese, include a fallback language, in this case Indonesian console.log(new Intl.DateTimeFormat(["ban", "id"]).format(date)); // "19/12/2012"
Using options
The date and time formats can be customized using the options argument:
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200)); // request a weekday along with a long date let options = weekday: "long", year: "numeric", month: "long", day: "numeric", >; console.log(new Intl.DateTimeFormat("de-DE", options).format(date)); // "Donnerstag, 20. Dezember 2012" // an application may want to use UTC and make that visible options.timeZone = "UTC"; options.timeZoneName = "short"; console.log(new Intl.DateTimeFormat("en-US", options).format(date)); // "Thursday, December 20, 2012, GMT" // sometimes you want to be more precise options = hour: "numeric", minute: "numeric", second: "numeric", timeZone: "Australia/Sydney", timeZoneName: "short", >; console.log(new Intl.DateTimeFormat("en-AU", options).format(date)); // "2:00:00 pm AEDT" // sometimes you want to be very precise options.fractionalSecondDigits = 3; //number digits for fraction-of-seconds console.log(new Intl.DateTimeFormat("en-AU", options).format(date)); // "2:00:00.200 pm AEDT" // sometimes even the US needs 24-hour time options = year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", hour12: false, timeZone: "America/Los_Angeles", >; console.log(new Intl.DateTimeFormat("en-US", options).format(date)); // "12/19/2012, 19:00:00" // to specify options but use the browser's default locale, use undefined console.log(new Intl.DateTimeFormat(undefined, options).format(date)); // "12/19/2012, 19:00:00" // sometimes it's helpful to include the period of the day options = hour: "numeric", dayPeriod: "short" >; console.log(new Intl.DateTimeFormat("en-US", options).format(date)); // 10 at night
The used calendar and numbering formats can also be set independently via options arguments:
const options = calendar: "chinese", numberingSystem: "arab" >; const dateFormat = new Intl.DateTimeFormat(undefined, options); const usedOptions = dateFormat.resolvedOptions(); console.log(usedOptions.calendar); // "chinese" console.log(usedOptions.numberingSystem); // "arab" console.log(usedOptions.timeZone); // "America/New_York" (the users default timezone)
Specifications
Browser compatibility
BCD tables only load in the browser
See also
How to Format a Date with JavaScript – Date Formatting in JS
Joel Olawanle
Dates are a fundamental part of many JavaScript applications, whether it’s displaying the current date on a webpage or handling user input for scheduling events.
But displaying dates in a clear and consistent format is crucial for a positive user experience.
In the past, I have written two articles on Date formatting. The first explained solely how to use the toLocaleDateString() method to format dates, while the second explained custom date formatting with the getFullYear() , getMonth() , and getDate() methods.
In this article, we’ll explore various techniques to format dates in JavaScript, enabling you to present dates in your desired format for your application.
How to Use the JavaScript Date Object
Before we dive into date formatting, let’s get familiar with the JavaScript Date object. It provides methods to work with dates and times effectively.
To create a new date instance, you can use the new Date() constructor.
const currentDate = new Date(); console.log(currentDate); // Wed May 31 2023 08:26:18 GMT+0100 (West Africa Standard Time)
The above code will output the current date and time in the default format. However, this format is not suitable for all use cases.
This is why we need to format dates so we can extract what we need from this date object.
In JavaScript, there is no direct syntax that provides you with your expected format because date format varies based on location, circumstance, and so on.
Basic JavaScript Date Formatting Methods
JavaScript provides a few built-in methods to format dates conveniently. Let’s take a look at some of these methods:
- toDateString(): This method converts the date portion of a Date object into a human-readable string format.
const date = new Date(); console.log(date.toDateString());
- toISOString(): This method converts a Date object into a string representation following the ISO 8601 format.
const date = new Date(); console.log(date.toISOString());
- toLocaleDateString(): This method returns a string representing the date portion of a Date object using the system’s local conventions.
const date = new Date(); console.log(date.toLocaleDateString());
Output: 5/30/2023 . This Format may vary based on the system’s locale. For more explanation on how this method works, read this article.
Custom Date Formatting in JavaScript
While the basic formatting methods can be useful in certain scenarios, you might often need more control over the date format.
JavaScript provides a couple ways to achieve custom date formatting:
- String Concatenation: One approach is to manually concatenate the different components of a date using string manipulation.
const date = new Date(); const formattedDate = `$-$-$`; console.log(formattedDate);
You can manipulate this however you like and come up with more creative ways of representing dates. You can read this article to understand custom date formatting in detail and this article on how to format dates with ordinal number suffixes (-st, -nd, -rd, -th) in JavaScript.
- Intl.DateTimeFormat: JavaScript’s Intl object offers powerful formatting capabilities through the DateTimeFormat object. It provides localization support and various options to format dates and times.
const date = new Date(); const formatter = new Intl.DateTimeFormat('en-US', < dateStyle: 'short' >); const formattedDate = formatter.format(date); console.log(formattedDate);
Using Intl.DateTimeFormat , you can specify the desired locale and various options to format dates precisely as needed. There are more options you can use in the official documentation.
How to Handle Time Zones When Working with Dates
When working with dates, it’s essential to consider time zones, especially when dealing with global applications or time-sensitive information.
JavaScript provides methods to handle time zones effectively:
- Time Zone Offset: The getTimezoneOffset() method of the Date object returns the difference in minutes between the local time zone and UTC. You can use this offset to adjust dates for specific time zones.
- Displaying Time Zones: To display the time zone information alongside the date, you can use the toLocaleString() method with the appropriate options.
const date = new Date(); const formattedDate = date.toLocaleString('en-US', < timeZoneName: 'short' >); console.log(formattedDate);
Output: 5/30/2023, 12:00:00 AM PDT .
Common Date Formatting Patterns
Certain date formatting patterns are commonly used. Here are a few examples:
- Specific Date Format: To display a date in a specific format, such as DD/MM/YYYY , you can use Intl.DateTimeFormat with the appropriate options.
const date = new Date(); const formatter = new Intl.DateTimeFormat('en-US', < day: '2-digit', month: '2-digit', year: 'numeric' >); const formattedDate = formatter.format(date); console.log(formattedDate);
- Time Format: To format the time portion of a date, you can use the hour , minute , and second options.
const date = new Date(); const formatter = new Intl.DateTimeFormat('en-US', < hour: '2-digit', minute: '2-digit', second: '2-digit' >); const formattedTime = formatter.format(date); console.log(formattedTime);
How to Handle Date Input
Apart from formatting dates for display, it’s essential to handle user input for dates effectively. Here are a few considerations:
- Parsing User Input: Use the Date.parse() method or external libraries like Moment.js or Luxon to parse user-provided dates into valid Date objects.
- Validating User Input: Implement validation mechanisms to ensure the user’s input adheres to the expected date format. Regular expressions or external libraries can help with this.
Wrapping Up
Formatting dates in JavaScript is an essential skill when building web applications. By utilizing the built-in date formatting methods, custom formatting techniques, and external libraries, you can ensure dates are presented clearly and accurately.
Experiment with different approaches and stay mindful of time zones for a seamless user experience with date formatting in JavaScript.
For further study on how to format dates, check these resources:
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.