Get the Day Name from a specific Date using JavaScript

avatar

Borislav Hadzhiev

Tue Jan 18 20222 min read

banner

Photo by Cody Black

Get the Day Name from a specific Date using JavaScript #

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.

index.js
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.

If no parameters are provided, the function returns the day name for the current date using the 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:

  1. 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.
  2. 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.

index.js
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.