Nick Maddren
Nick Maddren

Reputation: 583

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

Upvotes: 2

Views: 719

Answers (2)

Matt Lishman
Matt Lishman

Reputation: 1817

You can create a new date object with your stored date and compare them.

var today = new Date();

//Edited date slightly to make it fit javascript date format
var end = new Date("Thu Mar 01 2001 00:00:00 GMT+0000 (GMT)");

For example

if(today > end){
    //do something
}

Upvotes: 1

Alin P.
Alin P.

Reputation: 44346

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.

Upvotes: 1

Related Questions