Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 694
grasshopper Avatar asked Sep 18 '14 05:09

grasshopper


2 Answers

For weekdays, you could use moment's weekdays method

weekArray = moment.weekdays()
like image 127
Quentin F Avatar answered Oct 21 '22 23:10

Quentin F


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. E.g 'dddd' will shows:

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

Check Moment.js documentation for more advanced format

like image 21
Yunfei Li Avatar answered Oct 22 '22 00:10

Yunfei Li