For the last few days I was struggling with iterating through a range of dates. I was using following piece of code to test:
var current_date = new Date("2014-08-01");
var end_date = new Date("2014-10-31");
var end_date_time = end_date.getTime();
while (current_date.getTime() <= end_date_time) {
document.write(current_date + '<br>');
current_date.setDate(current_date.getDate()+1);
}
To me it looks correct, but there's a problem. It's missing the last day. I was turning this code around, used a for- loop, defined new Date within loop and all the things you can imagine. One thing stayed the same. Last day missing!
By curiosity I used following format to create the Dates:
var current_date = new Date("08/01/2014");
var end_date = new Date("10/31/2014");
And to my surprise, it worked as expected. Now I'm wondering if this is a normal behaviour or a bug in Date?
I would be thankfull, if someone can enlighten me.
that is because there was a change in time, check that the first days are in GMT Daylight Time and the lasts in (GMT Standard Time)
so your code better to use UTC
var current_date = new Date("2014-08-01");
current_date = new Date(current_date.getUTCFullYear(), current_date.getUTCMonth(), current_date.getUTCDate(), current_date.getUTCHours(), current_date.getUTCMinutes(), current_date.getUTCSeconds());
var end_date = new Date("2014-10-31");
end_date = new Date(end_date.getUTCFullYear(), end_date.getUTCMonth(), end_date.getUTCDate(), end_date.getUTCHours(), end_date.getUTCMinutes(), end_date.getUTCSeconds());
var end_date_time = end_date.getTime();
while (current_date <= end_date) {
document.write(current_date + '<br>');
current_date.setDate(current_date.getDate()+1);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments