我想使用 Moment.js 获取数组中特定年份的一个月中的所有日期。例如:
January-2014:
[
"01-wed",
"02-thr",
"03-fri",
"04-sat"
]
有什么建议吗?我查看了 Moment.js 文档,但找不到任何内容。我得到的壁橱是这样的:
moment("2012-02", "YYYY-MM").daysInMonth()
但这只返回一个包含特定月份总天数的整数,而不是包含每一天的数组。
最佳答案
这是一个可以解决问题的函数(不使用 Moment,而只使用 vanilla JavaScript):
var getDaysArray = function(year, month) {
var monthIndex = month - 1; // 0..11 instead of 1..12
var names = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
var date = new Date(year, monthIndex, 1);
var result = [];
while (date.getMonth() == monthIndex) {
result.push(date.getDate() + '-' + names[date.getDay()]);
date.setDate(date.getDate() + 1);
}
return result;
}
例如:
js> getDaysArray(2012,2)
["1-wed", "2-thu", "3-fri", "4-sat", "5-sun", "6-mon", "7-tue",
"8-wed", "9-thu", "10-fri", "11-sat", "12-sun", "13-mon", "14-tue",
"15-wed", "16-thu", "17-fri", "18-sat", "19-sun", "20-mon", "21-tue",
"22-wed", "23-thu", "24-fri", "25-sat", "26-sun", "27-mon", "28-tue",
"29-wed"]
ES2015+ 版本 - 还将名称数组隐藏在闭包后面,因此它只初始化一次:
const getDaysArray = (function() {
const names = Object.freeze([ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ]);
return (year, month) => {
const monthIndex = month - 1
const date = new Date(year, monthIndex, 1);
const result = [];
while (date.getMonth() == monthIndex) {
result.push(`${date.getDate()}-${names[date.getDay()]}`);
date.setDate(date.getDate() + 1);
}
return result;
}
})();
作为旁注,您可以看到声明日期 const
并不能阻止我们改变它(Object.freeze
也不会,用于使工作日名称数组不可变,对 Date
做任何事情)。我们在这里利用了可变性,但如果我们真的想要一个不可变的 Date 语言在当前 Javascript 中强制执行不可变性,我们必须 go to some length .
另请注意,与问题中包含的示例输出不同,上述解决方案不会对 10 号之前的日期进行零填充。使用 ES2017+ 很容易修复:
result.push(`${date.getDate()}`.padStart(2,'0') + `-${names[date.getDay()]}`);
在旧版本的 JS 中执行此操作需要滚动您自己的零填充逻辑,这并不难,但也不是问题的真正重点。
关于javascript - 如何使用 Moment.js 获取一个月中的天数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25588473/