Javascript 使用 moment js 创建一个包含一周中的几天和一天中的几小时的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25905183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using moment js to create an array with days of the week and hours of the day?
提问by grasshopper
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.
想知道是否有办法获取 momentjs 或仅使用纯 javascript 来创建一周中的每一天和一天中的每个小时的数组,这样我就不必对其进行硬编码。
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.
特别是在白天的时候,同样的想法,所以我可能会使用不同的格式。
回答by Quentin F
For weekdays, you could use moment's weekdays method
对于工作日,您可以使用moment 的工作日方法
weekArray = moment.weekdays()
回答by Yunfei Li
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:
您可以修改 .format(string) 以更改日期格式。例如“dddd”将显示:
["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
Check Moment.js documentationfor more advanced format
查看Moment.js 文档以获得更高级的格式
回答by Robert K. Bell
Here's a little snippet to get the (locale-specific) names of the days of the week from Moment.js:
这是从 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').
如果您希望一周从星期一开始,请替换moment(i, 'e')为moment(i+1, 'e')。

