views:

179

answers:

3

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 Date("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

A: 

Hey,

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.

Brian
Ahh, it says invalid date, so maybe that's why it isn't working. The date string was originally created by jquery, so I assumed it would accept it back without any problems. So the question is what do I have to do to get it accept the date string?
chrism
+3  A: 
  1. You need to unescape the string:

    var then = new Date(decodeURIComponent("Thu ... "));
    
  2. There's no need to set new date instance's time like that - this does nothing:

    d.setTime(d.getTime());
    
  3. 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

Pointy
I've never seen unescape before (shows you how much I know about javascript) - is it used a lot in javascript/jquery, or is it specific to date/time?
chrism
@chrism: `unescape` and `escape` are deprecated, you should use `decodeURIComponent` and `encodeURIComponent` respectively. They are usually used for encoding and decoding url strings.
Andy E
I tried "decodeURI" on that string and it didn't get the "+" sign, but you're right: decodeURIComponent works and it'd be better. Updating answer; thanks @Andy!
Pointy
Changed to decodeURIComponent, thanks for the heads up
chrism
A: 

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

Andy E