I've recently been introduced to the Intl object, which is used as the namespace for the ECMAScript Internationalization API. It has a neat object called DateTimeFormat which can be used to format a date value into locale specific strings.
I'll show you a typical use case for using Intl.DateTimeFormat to generate the weekday of a given date string (e.g. 07/16/1945).
Problem
Given a dateString in the format MM/DD/YYYY, find and return the weekday for that date.
Solution
/**
* Given a date string in the format MM/DD/YYY, find and return the
* weekday for that date in English.
*
* @param {string} dateString
* @returns {string} - weekday for the given date [e.g: Wednesday]
*/
const getWeekDay = (dateString) => {
const date = new Date(dateString);
const dateTimeFormatOptions = { weekday: 'long' };
const dateTimeFormat = new Intl.DateTimeFormat('en-US', dateTimeFormatOptions);
return dateTimeFormat.format(date);
}
Explanation
- Create a function expression called
getWeekDaywhich takes a string (dateString). - Create a
Dateobject with the givendateString, so that we can pass it as a parameter into theformatmethod ofDateTimeFormat. - Create an object to hold the
optionsparameter forIntl.DateTimeFormat. Setting theweekdayproperty equals tolong, so that we get the localized weekday when callingformat. - Create a an instance of
Intl.DateTimeFormatsettinglocalestoen-US, and passing in the previously createddateTimeFormatOptionsobject. - Return the result of calling
formatmethod onIntl.DateTimeFormatto find the weekday for the givendate.
Output
console.log(getWeekDay("07/16/1945"));
// expected output: "Monday"
In closing, we used the Intl.DateTimeFormat object to quickly find the weekday of a given date string. Best of all Intl has great support across modern browser.
Thank you for reading.
Top comments (0)