Last updated: Mar 6, 2024
Reading timeยท2 min
Use the toLocaleDateString()
method to get the day name from a specific
date.
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.
I've also written an article on how to convert month number to month name and vice versa.
You can learn more about the related topics by checking out the following tutorials: