0

I was trying to compare two dates and time

se_time = 2017/05/16 17:41:47
curr_date = 2017/5/16 12:42:6

The result of "console.log(curr_date < se_time)" is false should not it be true?

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
Chetan
  • 469
  • 3
  • 12
  • 27
  • 4
    That is invalid syntax. – SLaks May 16 '17 at 16:47
  • Your dates when formatted as strings using the same date format would normally return the correct value because alphabetically they would have the same result. However, they aren't the same date format. In one you have numbers with leading zeroes and in the other you don't. You have the month in one as `05` and the other just `5` which would make them alphabetically incorrect as the sixth character `0 < 5`. You would also need to correct the seconds in the time. – Jonathan Kuhn May 16 '17 at 16:56

1 Answers1

1

You have to create the date object first, you cannot compare the strings as they are.

var date1 = new Date('2011-04-12T10:20:30Z');
var date2 = new Date('2011-04-11T10:20:30Z');
console.log(date1>date2);//true
  • How do I get the current date in "2011-04-11T10:20:30Z" format? Is there a build in function/ method for that? – Chetan May 16 '17 at 17:05
  • You can still use the format you listed. I've updated this answer to reflect that. – Eric C. Bohn May 16 '17 at 17:19
  • No, don't do that. ECMA-262 only requires ISO 8601 extended format to be parsed, any other format is implementation dependent and may be incorrectly parsed or return an invalid Date. Write a small parsing function (maybe 3 or 4 lines of code) or use a library. See [*Why does Date.parse give incorrect results?*](http://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG May 16 '17 at 20:56