1

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

3 Answers 3

3
  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

Sign up to request clarification or add additional context in comments.

3 Comments

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: unescape and escape are deprecated, you should use decodeURIComponent and encodeURIComponent respectively. They are usually used for encoding and decoding url strings.
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!
0

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.

1 Comment

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?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.