如何使用Moment.js获取一个月内的天数列表 [英] How to get list of days in a month with Moment.js
问题描述
使用Moment.js我希望在一个特定年份的某个月中获得阵列中的所有日子。例如:
Using Moment.js I would like to get all days in a month of specific year in an array. For example:
January-2014:
[
"01-wed",
"02-thr",
"03-fri",
"04-sat"
]
有什么建议吗?我查看了Moment.js文档但找不到任何内容。我得到的壁橱是:
any suggestions? I looked through Moment.js docs but couldn't find anything. The closet I got was this:
moment("2012-02", "YYYY-MM").daysInMonth()
但这只返回一个int,其中特定月份的总天数不是每天的数组。
But this only return an int with total days for specific month not an array with each day.
推荐答案
这是一个可以解决问题的功能(不使用Moment,只是vanilla JavaScript):
Here's a function that will do the trick (not using Moment, but just vanilla JavaScript):
var getDaysArray = function(year, month) {
var names = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
var date = new Date(year, month - 1, 1);
var result = [];
while (date.getMonth() == month - 1) {
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 +版本:
ES2015+ version:
const getDaysArray = (year, month) => {
const names = Object.freeze(
[ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ]);
const date = new Date(year, month - 1, 1);
const result = [];
while (date.getMonth() == month - 1) {
result.push(`${date.getDate()}-${names[date.getDay()]}`);
date.setDate(date.getDate() + 1);
}
return result;
}
请注意,上述解决方案不会在10日之前进行零填充日期,与问题中包含的示例输出不同。使用ES2017 +非常容易修复:
Do note that the solutions above don't zero-pad dates before the 10th, unlike the sample output included in the question. With ES2017+ that's pretty easy to fix:
result.push(`${date.getDate()}`.padStart(2,'0') + `-${names[date.getDay()]}`);
在旧版本的JS中执行它需要滚动自己的零填充逻辑,这并不困难但这也不是问题的重点。
Doing it in older versions of JS requires rolling your own zero-padding logic, which isn't hard but is also not really the focus of the question.
这篇关于如何使用Moment.js获取一个月内的天数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!