0

I have a date with the format 2017-03-29T06:45:00.000Z, how do I check if it is equal or less to the date and time now?

If I check with

var currentTime = new Date();
if("2017-03-29T06:45:00.000Z" <= currentTime){

its not right since current date is in the format Wed Mar 29 2017 08:59:18 GMT+0200(CEST) Any input appreciated, thanks

Claes Gustavsson
  • 5,509
  • 11
  • 50
  • 86

1 Answers1

2

You are trying to compare a string to a Date Object. Because the two data types do not match, javascript tries to compare them by their value and calls currentTime.valueOf(). This evaluates to a integer like 1490781568805. Javascript then tries to compare the string to the evaluated integer. The result is different than you might expect, because the individual char codes of the string are compared to the integer.

"2017-03-29T06:45:00.000Z" <= new Date() // string compared to the Date object
"2017-03-29T06:45:00.000Z" <= new Date().valueOf() // javascript trying get a value for the date object
"2017-03-29T06:45:00.000Z" <= 1490781568805 // evaluates to false

You can just parse your date string to a Date object using Date.parse()

Date.parse("2017-03-29T06:45:00.000Z") <= new Date() // two Date objects are compared
Community
  • 1
  • 1