getDayName
Returns the name of the weekday for a given date.
1/**
2 * Returns the name of the weekday for a given date.
3 *
4 * @param date - The date to extract the day name from.
5 * @param locale - Optional locale string (default is 'en-US').
6 * @param format - Optional format: 'long', 'short', or 'narrow' (default is 'long').
7 * @returns The day name in the specified locale and format.
8 */
9export function getDayName(
10 date: Date,
11 locale: string = 'en-US',
12 format: 'long' | 'short' | 'narrow' = 'long'
13): string {
14 return new Intl.DateTimeFormat(locale, { weekday: format }).format(date);
15}
Locale Support
Utilizes the native
Intl.DateTimeFormat
API, making the function fully internationalized and adaptable to any supported locale.Flexible Output Formats
Supports
'long'
,'short'
, and'narrow'
formats, allowing developers to match various UI contexts (e.g., full names or abbreviations).No External Dependencies
Built entirely on built-in browser capabilities, avoiding the need for moment.js or date-fns for this specific use case.
Minimal Input Required
Defaults to
'en-US'
locale and'long'
format, making it convenient to use in most cases without specifying extra parameters.
Tests | Examples
1test('returns full weekday name (default)', () => {
2 const date = new Date('2025-06-27'); // Friday
3 expect(getDayName(date)).toBe('Friday');
4});
5
6test('returns short weekday name', () => {
7 const date = new Date('2025-06-27');
8 expect(getDayName(date, 'en-US', 'short')).toBe('Fri');
9});
10
11test('returns narrow weekday name', () => {
12 const date = new Date('2025-06-27');
13 expect(getDayName(date, 'en-US', 'narrow')).toBe('F');
14});
15
16test('returns weekday name in different locale', () => {
17 const date = new Date('2025-06-27');
18 expect(getDayName(date, 'fr-FR')).toBe('vendredi');
19});
Common Use Cases
Calendar UI Labels
Display human-readable day names (e.g. “Monday”, “Tue”) in scheduling or booking interfaces.
Date Pickers
Enhance accessibility and clarity by showing day names alongside dates.
Event or Reminder Summaries
Provide more readable time references in phrases like “Meeting on Thursday”.
Localized Interfaces
Generate weekday names in the user’s preferred language/region settings.
Graph or Report Axes
Label chart axes or data groupings by weekday with short or narrow formatting.