How to get list of weekdays from mon to sun in moment.js?

by elisha_langworth , in category: Javascript , a year ago

How to get list of weekdays from mon to sun in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , a year ago

@elisha_langworth 

You can use the weekdays() method in Moment.js to get the list of weekdays from Monday to Sunday. Here's an example:

1
2
3
4
5
const moment = require('moment');

const weekdays = moment.weekdays();

console.log(weekdays); // Output: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']


In the above example, moment.weekdays() returns an array of weekdays starting from Sunday by default. To get the weekdays starting from Monday, you can use the weekday() method as follows:

1
2
3
4
5
6
7
8
const weekdays = [];
const startDay = moment().startOf('isoWeek'); // Get the start of the current week

for (let i = 0; i < 7; i++) {
  weekdays.push(startDay.clone().add(i, 'day').format('dddd'));
}

console.log(weekdays); // Output: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']


This code starts at the beginning of the current week (startOf('isoWeek')) and adds each day of the week to the weekdays array using startDay.clone().add(i, 'day'). The format('dddd') is used to get the full name of the weekday.