Search code examples
javascriptdate-comparison

If new Date is less than date stored in variable


I am just wondering how I can compare a date with the following code:

var today = new Date();

Outputs the current day like so:

Wed Feb 24 2016 12:02:34 GMT+0000 (GMT Standard Time)

However if I have a variable containing a string like so:

var end = "Tue Mar 1 2016 00.00.00 GMT+0000 (GMT Standard Time)";

I am unable to compare these two variables in an if statement using the greater than operator because the end variable is a string.

So I am just wondering how I can compare a set date in a variable with my today variable?

Thanks, Nick


Solution

  • You can use the timestamp of the date, instead of the string representation.

    var today = new Date();
    console.log(today.getTime());
    

    That's an integer and you can compare two of those. Keep in mind that this is a milliseconds timestamp, and not a seconds one, if you want to compare it with timestamps from other sources.

    Note: There's also the option to parse back from the string representation of the time to Date object, but that depends a lot on the format the string was composed in (and possibly the JS client) and it may not always work. I recommend to only work with numeric timestamps if you plan on comparing times.