I want to show all dates between two days.I can't do this.Please help.. This is my code...
var Day = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date("2017-04-10");
var secondDate = new Date("2017-04-15");
var diffDays = (secondDate.getTime() - firstDate.getTime())/Day;
alert(diffDays);
for(var i=0;i<= diffDays ;i++)
{
var d = new Date(firstDate + i);
alert(d);
}
答案 0 :(得分:1)
您的i
变量是当天的数字。您的firstDate
变量是Date
。
这一行:
var d = new Date(firstDate + i);
将这些添加在一起并尝试创建新的Date
。由于这些是不同的类型(日期和数字)类型强制起作用(即:日期和数字转换为字符串,并连接在一起)。
试试这个:
var DAY_IN_MS = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var theDate = new Date("2017-04-10");
var i = 5;
// Date + Number = Type Coercion! Both objects will be converted to strings and concatenated together.
alert(theDate + i);
// The Date constructor doesn't care, and will work because it can get a date from the first part of the string.
alert(new Date(theDate + i));
// If you use `getTime()` you can get the numerical value of the Date, which you can use for arithmetic.
alert(theDate.getTime());
// By adding `i`, however, you are only adding a few milliseconds to the first date !!
alert(new Date(theDate.getTime() + i);
// Number + Number of days times milliseconds per day = success!
alert(new Date(theDate.getTime() + (i * DAY_IN_MS)));
我认为你的意思是:
var d = new Date(firstDate.getTime() + (i * Day));
答案 1 :(得分:0)
简短回答,将正确的毫秒数增加到firstDate.getTime()
:
for(var i=0;i<= diffDays ;i++)
{
firstDate = new Date(firstDate.getTime() + Day);
console.log(firstDate);
}
答案很长,你的代码中有几个问题:
此处var d = new Date(firstDate + i);
添加到Date对象字符串表示中,i
的值在这种情况下在循环中递增。
然后,您将此String解析为新的Date对象,但Javascript仅识别日期并忽略附加的数字
您应该像firstDate
那样尝试获得diffDays
的毫秒数,然后添加i * Day
(还要考虑将此变量重命名为其他内容,可能是const DAY_IN_MS
或者什么)。