2

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

Jahangir Alam
  • 311
  • 2
  • 11
Nick Maddren
  • 583
  • 2
  • 7
  • 19

2 Answers2

1

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.

Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
  • you'll need to convert the variable end to a date and then compare them as Date("end variable string") – Taran J Feb 24 '16 at 12:17
  • @TaranJ See the comment I left to Matt's answer to understand why that may be a bad idea. – Alin Purcaru Feb 24 '16 at 12:18
  • Yep, still you'll need to convert the string to Date Object and then obtain its timestamp using getTime – Taran J Feb 24 '16 at 12:41
  • How could you compare this to the `end` date without using a date object though? As @TaranJ said, you would still need to do `getTime()` – Matt Lishman Feb 24 '16 at 13:01
1

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
}
Matt Lishman
  • 1,817
  • 2
  • 22
  • 34