Easy Way To Find Weekday From a Given Date String
Luiz Lopes
Posted on May 30, 2019
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
getWeekDay
which takes a string (dateString
). - Create a
Date
object with the givendateString
, so that we can pass it as a parameter into theformat
method ofDateTimeFormat
. - Create an object to hold the
options
parameter forIntl.DateTimeFormat
. Setting theweekday
property equals tolong
, so that we get the localized weekday when callingformat
. - Create a an instance of
Intl.DateTimeFormat
settinglocales
toen-US
, and passing in the previously createddateTimeFormatOptions
object. - Return the result of calling
format
method onIntl.DateTimeFormat
to 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.
💖 💪 🙅 🚩
Luiz Lopes
Posted on May 30, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.