Search code examples
date-fns

How can I get the days of the week from date-fns?


I want to get an array of ['Sun', 'Mon',...] based on whatever localizations are set with date-fns. Ideally, I can apply format to modify to my goals.

Any help would be greatly appreciated. Thanks!


Solution

  • You can use the format function from the date-fns library to achieve this.

    import { format, eachDayOfInterval } from 'date-fns';
    import { enUS } from 'date-fns/locale';
    
    const daysOfWeek = eachDayOfInterval({ start: new Date(), end: new Date(new 
                      Date().setDate(new Date().getDate() + 6)) });
    
    const weekdays = daysOfWeek.map((day) => format(day, 'EEE', { locale: enUS }));
    
    console.log(weekdays); // ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
    

    Here, first create an array of the following seven days starting from today's date using the eachDayOfInterval method. The format function is then used with the format string "EEE" to produce the shortened weekday name after looping through each day using the map function (e.g. "Sun", "Mon", "Tue", etc.). To guarantee that the weekday names are created using the English (US) locale, then supply the enUS locale object as an option to the format function.