JS-获取星期几 [英] JS- Get days of the week
本文介绍了JS-获取星期几的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个函数以获取给定日期的一周中的所有天。我有一个我认为一直有效的函数,直到我注意到如果一周中的某天接近月底,例如2月,我得到了奇怪的数据。任何人都知道发生了什么事以及如何解决它?
I'm trying to make a function to get all the days of the week given the current day.I had a function that i thought was working until i noticed that if the day of the week is near the end of the month, like for example February, i get weird data. Anyone know whats going on and how to fix it?
function days(current) {
var week = new Array();
// Starting Monday not Sunday
var first = ((current.getDate() - current.getDay()) + 1);
for (var i = 0; i < 7; i++) {
week.push(
new Date(current.setDate(first++))
);
}
return week;
}
var input = new Date(2017, 1, 27);
console.log('input: %s', input);
var result = days(input);
console.log(result.map(d => d.toString()));
.as-console-wrapper{min-height:100%}
推荐答案
如果您不想使用诸如Moment.js之类的其他类型的库,则还可以稍微更改一下函数,然后它就会起作用。试试这个:
If you don't want to use some kind of other library like Moment.js you can also change your function a little and then it will work. Try this:
function dates(current) {
var week= new Array();
// Starting Monday not Sunday
current.setDate((current.getDate() - current.getDay() +1));
for (var i = 0; i < 7; i++) {
week.push(
new Date(current)
);
current.setDate(current.getDate() +1);
}
return week;
}
console.log(dates(new Date(2017, 1, 27)));
这篇关于JS-获取星期几的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文