简体   繁体   中英

Using moment js to create an array with days of the week and hours of the day?

Wondering if there was a way to get momentjs or just use pure javascript to create an array of everyday of the week, and every hour in a day so that I dont have to hardcode it.

So instead of manually doing

weekArray = ["Monday", "Tuesday", "Wednesday" ....]

I'm looking for a way to do something like

weekArray = moment.js(week)

The same idea for times during the day especially, so I could potentially use different formats.

对于工作日,您可以使用时刻的工作日方法

weekArray = moment.weekdays()

I use this solution:

var defaultWeekdays = Array.apply(null, Array(7)).map(function (_, i) {
    return moment(i, 'e').startOf('week').isoWeekday(i + 1).format('ddd');
});

I got result:

["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

You can Modify .format(string) to change the days format. Eg 'dddd' will shows:

["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

Check Moment.js documentation for more advanced format

Here's a little snippet to get the (locale-specific) names of the days of the week from Moment.js:

var weekdayNames = Array.apply(null, Array(7)).map(
    function (_, i) {
        return moment(i, 'e').format('dddd');
    });
console.log(weekdayNames);
// Array [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]

If you want the week to start on Monday, replace moment(i, 'e') with moment(i+1, 'e') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM