I have been passed a date string that looks like this:
Thu%20Mar%2011%202010%2015%3A09%3A11%20GMT%2B0000%20(BST)
I want to compare this date with today's date and hopefully ascertain whether the string above has happened yet. With my limited knowledge of jquery/javascript I wrote this:
var str = new Da开发者_Python百科te("Thu%20Mar%2011%202010%2015%3A09%3A11%20GMT%2B0000%20(BST)");
var date = new Date();
date.setTime(date.getTime());
if (date > str) {
alert('This date has passed');
} else {
alert('This date has NOT passed');
}
However this always returns the second result, even though The date string has definitely passed (it was for about twenty minutes ago as of time of posing). Where am I going wrong
You need to unescape the string:
var then = new Date(decodeURIComponent("Thu ... "));
There's no need to set new date instance's time like that - this does nothing:
d.setTime(d.getTime());
You need to compare the values returned by getTime() for each date object
var then = new Date(decodeURIComponent("Thu ... ")); var now = new Date(); if (now.getTime() > then.getTime()) { ... }
edited to change unescape
to decodeURIComponent
If you do alert(str), what does it return? Maybe it's having trouble dealing with the encodings that it's returning an undefined or something. Maybe doing unescape would help before you create the date.
You can't pass a string like that to the Date
constructor. Passing that string would make it return the current date/time instead and, since the date
variable is created after, there's a chance it would be at least 1ms greater than the str
variable.
Make sure you pass a parseable string to the Date
constructor, it needs to be in a format parseable by Date.parse
精彩评论