HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Weekday name from a JavaScript Date object

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptdateobjectfromweekdayname

Problem

Date objects in JavaScript have a lot of useful methods, even though they often get a bad rap. One of these methods is Date.prototype.toLocaleDateString(), which can be used to get the name of the weekday from a Date object.
To get the full name of the weekday, you can use the { weekday: 'long' } option with Date.prototype.toLocaleDateString(). If you want to get the name in a specific language, you can pass a second argument to the following function, specifying the locale code.
Similarly, you can get the short name of the weekday by using the { weekday: 'short' } option. This will return the abbreviated name of the weekday (e.g., 'Mon', 'Tue', 'Wed').
If you only need the first letter of the weekday name, you can use the { weekday: 'narrow' } option. Note that this will return the first letter of the weekday name, which might not be unique (e.g., 'T' for both 'Tuesday' and 'Thursday').

Solution

const dayName = (date, locale) =>
  date.toLocaleDateString(locale, { weekday: 'long' });

dayName(new Date()); // 'Monday'
dayName(new Date('05/27/2024'), 'de-DE'); // 'Montag'


Similarly, you can get the short name of the weekday by using the { weekday: 'short' } option. This will return the abbreviated name of the weekday (e.g., 'Mon', 'Tue', 'Wed').
If you only need the first letter of the weekday name, you can use the { weekday: 'narrow' } option. Note that this will return the first letter of the weekday name, which might not be unique (e.g., 'T' for both 'Tuesday' and 'Thursday').

Code Snippets

const dayName = (date, locale) =>
  date.toLocaleDateString(locale, { weekday: 'long' });

dayName(new Date()); // 'Monday'
dayName(new Date('05/27/2024'), 'de-DE'); // 'Montag'
const shortDayName = (date, locale) =>
  date.toLocaleDateString(locale, { weekday: 'short' });

shortDayName(new Date()); // 'Mon'
shortDayName(new Date('05/27/2024'), 'de-DE'); // 'Mo'
const narrowDayName = (date, locale) =>
  date.toLocaleDateString(locale, { weekday: 'narrow' });

narrowDayName(new Date()); // 'M'
narrowDayName(new Date('05/27/2024'), 'de-DE'); // 'M'

Context

From 30-seconds-of-code: weekday-name

Revisions (0)

No revisions yet.