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"

]

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()

But this only return an int with total days for specific month not an array with each day.

解决方案

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;

}

For example:

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+ 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;

}

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()]}`);

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值