Internationalizing Dates (Intl) In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Internationalizing Dates (Intl) In JavaScript.
Internationalizing Dates (Intl) In JavaScript
In JavaScript, you can use the Intl
object to internationalize dates. The Intl
object provides a set of functions for formatting and parsing dates, times, numbers, and currencies according to different locales.
To format a date using Intl
, you can use the DateTimeFormat
constructor. The constructor takes two arguments: the locale and an options object. The options object can be used to specify various formatting options, such as the date style and the time zone.
Here’s an example that formats a date using the user’s locale and the default formatting options:
const date = new Date();
const formatter = new Intl.DateTimeFormat();
const formattedDate = formatter.format(date);
console.log(formattedDate);
This will output the date in the user’s locale using the default formatting options.
You can also customize the formatting options by passing an options object to the DateTimeFormat
constructor. Here’s an example that formats a date using a specific locale and custom formatting options:
const date = new Date();
const options = { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', timeZone: 'America/Los_Angeles' };
const formatter = new Intl.DateTimeFormat('en-US', options);
const formattedDate = formatter.format(date);
console.log(formattedDate);
This will format the date using the “en-US” locale, and will display the year, month, day, hour, and minute, in a long format, according to the Pacific Time Zone (America/Los_Angeles).
To format a date in the Indian Standard Time (IST) timezone, you can pass the timeZone
option to the Intl.DateTimeFormat
constructor with the value “Asia/Kolkata”, which is the timezone identifier for IST.
Here’s an example:
const date = new Date();
const options = { timeZone: 'Asia/Kolkata', weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const formatter = new Intl.DateTimeFormat('en-IN', options);
const formattedDate = formatter.format(date);
console.log(formattedDate);
In this example, the options
object specifies that the date should be formatted with the full weekday name, the full month name, and the year and day in numeric format. The timeZone
option is set to “Asia/Kolkata” to format the date in IST.
The Intl.DateTimeFormat
constructor takes two arguments: the first argument is the locale, which is set to “en-IN” to use the English language and the Indian region format.