Reputation: 9
http://jsfiddle.net/7vzapm49/1/
var startdatearr = [new Date("04 Dec 2014 14:30:00").toUTCString(), new Date("07 Dec 2014 14:30:00").toUTCString()];
var enddatearr = [new Date("05 Dec 2014 14:30:00").toUTCString(), new Date("08 Dec 2014 14:30:00").toUTCString()];
var d = new Date().toUTCString();
for (i = 0; i < startdatearr.length; i++) {
if (startdatearr[i] <= d && d <= enddatearr[i]) {
alert("true");
} else {
alert("false");
}
}
This piece of code used to work, but suddenly it doesn't, even if I check the date today it seemingly says that UTC is between 4th and 5th of December 2014, but it still returns false.
Does the code not work in December, or have I been using deprecated code?
Upvotes: 0
Views: 42
Reputation: 59232
You have to make it into milliseconds and then compare it. It will then work correctly. As of now you're comparing strings which I suppose follows lexical pattern.
var startdatearr = [+new Date("04 Dec 2014 14:30:00"), +new Date("07 Dec 2014 14:30:00")];
var enddatearr = [+new Date("05 Dec 2014 14:30:00"), +new Date("08 Dec 2014 14:30:00")];
var d = +new Date();
for (i = 0; i < startdatearr.length; i++) {
if (startdatearr[i] <= d && d <= enddatearr[i]) {
alert("true");
} else {
alert("false");
}
}
To again convert the milliseconds to date and then showing UTC string, you could do
alert(new Date(d).toUTCString());
alert(new Date(startdatearr[0]).toUTCString());
alert(new Date(enddatearr[0]).toUTCString());
Upvotes: 1
Reputation: 15104
In a UTC date, the first part of the string is the day of the week. For example, "04 Dec 2014 14:30:00"
in UTC is "Thu, 04 Dec 2014 13:30:00 GMT"
.
So when you compare d
and startdatearr[i]
, most of the times you only check which day of the week is the first in the alphabetical order.
So this code may works or not, dependings of the day of the week.
Upvotes: 1
Reputation: 25419
Well, you are running a ToString flavor method. If this previously worked, I suspect that it only worked per chance. As the startdatearr[i] <= d
would have been checking if strings are less than or equal to. If there is any inherit conversion taking place, that would be browser / JS implementation specific and not dependable.
What might work, depending on your goal and needs for UTC, is remove each call to .toUTCString()
and just use the Date
object returned but this will be localized to the browser's timezone (again, depending on JS implementation but I'm assuming a browser is running this code).
Upvotes: 1