如何创建一个for循环,该循环返回一个月内使用javascript的剩余天数的新日期对象数组 [英] How to create a for loop which returns an array of new date objects for remaining days in a month using javascript
问题描述
我需要返回一个包含Date对象的数组,为循环创建新的Date()
对象设置为当月剩余的每一天,将它们添加到数组并返回数组。 p>
我想出了代码来检索月份中的剩余日期,但是由于某些原因,我无法确定循环/数组部分。
这里是我的代码:
pre $函数findDays(theDate){
var now = new Date();
var date = now.getDate();
var last = new Date(now.getFullYear(),now.getMonth()+ 1,0).getDate();
返回last - date;
console.log(findDays() - (new Date(2016,0,1))。getDate());
您可以使用 getTime 和
setTime
Date对象的方法一次提前一天。
var days = [];
var now = new Date();
var day = new Date(now.getFullYear(),now.getMonth(),now.getDate(),0,0,0,0); (day.getMonth()=== now.getMonth()){
days.push(day);
while(day.getMonth
//转到第二天
day = new Date(day.getTime()+ 86400000); //每天有86400000毫秒
I need to return an array containing a Date object for each day remaining in the month, for a given Date.
I need a for
loop that creates new Date()
objects set to each day remaining in the month, adding them to an array and returning the array.
I came up with the code to retrieve the remaining days in the month, however I can't figure the loop / array part out for some reason.
Here is my code:
function findDays(theDate) {
var now = new Date();
var date = now.getDate();
var last = new Date(now.getFullYear(), now.getMonth()+1, 0).getDate();
return last - date;
}
console.log(findDays() - (new Date(2016, 0, 1)).getDate());
You can use the getTime
and setTime
methods of the Date object to advance one day at a time.
var days = [];
var now = new Date();
var day = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
while (day.getMonth() === now.getMonth()) {
days.push(day);
// Go to the next day
day = new Date(day.getTime() + 86400000); // There are 86400000 milliseconds in a day
}
这篇关于如何创建一个for循环,该循环返回一个月内使用javascript的剩余天数的新日期对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!