Borislav Hadzhiev
Tue Jan 18 2022·2 min read
Photo by Cody Black
Use the toLocaleDateString()
method to get the day name from a specific
date, e.g. date.toLocaleDateString('en-US', {weekday: 'long'})
. The method
returns a string with language sensitive representation of the date portion of
the given date.
function getDayName(date = new Date(), locale = 'en-US') { return date.toLocaleDateString(locale, {weekday: 'long'}); } // ✅ Get name of current day console.log(getDayName()); // 👉️ Tuesday // ✅ Get day name for specific date console.log(getDayName(new Date('2022-01-29'))); // 👉️ Saturday // ✅ Get day name in different locale // 👇️ Samstag console.log(getDayName(new Date('2022-01-29'), 'de-DE'));
We created a reusable function that takes a Date
object and a locale as
parameters and returns the name of the given date.
en-US
locale.We used the toLocaleDateString method to get a string with language sensitive representation of the current date.
The 2 parameters we passed to the method are:
locales
- a string with a BCP 47 language tag or an array of such strings.
You can use any of the available locales, e.g. es-MX
for Mexico or en-CA
for Canada. If you need more information about this parameter, check out the
MDN docs.options
object, where we set the weekday
property. Read more about the
options
object in the
MDN docs.The weekday
property of the options
object is the representation of the
weekday.
We set it to long
to get the full name of the weekday. The possible values
include:
long
- (e.g. Thursday)short
- (e.g. Thu)narrow
- (e.g. T). Two weekdays may have the same narrow style for some
locales, e.g. Thursday and Tuesday are both T
.Note that the function we created has to be passed a Date()
object as a
parameter.
If you have a date string like 2022-04-29
, you should pass the string to the
Date()
constructor to create a Date
object when calling the function.
function getDayName(date = new Date(), locale = 'en-US') { return date.toLocaleDateString(locale, {weekday: 'long'}); } const dateStr = '2022-04-29'; // 👇️ "Friday" console.log(getDayName(new Date(dateStr))); // 👇️ "Freitag" console.log(getDayName(new Date(dateStr), 'de-DE'));
Passing a valid date or date and time string to the Date()
constructor returns
a Date
object, on which we can call the toLocaleDateString
method.