18

Is it safe to directly compare ISO Date Strings like this:

"2018-03-16T18:00:00.000z" > "2018-04-16T18:00:00.000z" // false

It seems as long as leading zeros are used (proper ISO formatting) this comparison is safe and there is no need to convert the values to Date Objects. Am I overlooking something?

Slbox
  • 10,957
  • 15
  • 54
  • 106

2 Answers2

9

With the given format of a ISO 8601 time,

2018-03-16T18:00:00.000Z
                       ^

you could use a direct string comparison, because the given time zone is a

Coordinated Universal Time (UTC)

If the time is in UTC, add a Z directly after the time without a space. Z is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".

Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

To answer your question comparing dates is tricky. I like to convert to something that is a little more concrete. Maybe not the most efficient answer, but it works for comparing dates.

var d = new Date();
var d1 = new Date();

console.log(d);
console.log(d1);

console.log(d.getTime());
console.log(d1.getTime());
console.log(d.getTime() === d1.getTime()); // true

Converting both to a number for a more valid comparison. Pulling the property off of the object itself.

http://jsbin.com/siwokibovi/edit?js,console

Dylan Wright
  • 1,118
  • 12
  • 19
  • 1
    Is it really a more valid comparison though? Can you demonstrate any edge cases where direct string comparison fails to yield the expected result when using UTC timezone? – Slbox Mar 16 '18 at 23:35
  • The answer to that would be no. Comparing strings to me is a bit of a wildcard, I would prefer to compare something like a number as to my eyes 1 = 1, yet 1 = 1.00 is also true or 1 = "1" but that is something more of what strings provide, variety. UTC comparison works but what if you don't have that format, you'd have to convert. Just pulling the value of getTime() has been the simpler approach for me. Not right, not wrong. – Dylan Wright Mar 19 '18 at 14:15