22

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?

4
  • 6
    As long as they are in the same timezone you can compare them as strings. Commented Mar 16, 2018 at 18:43
  • it should be an upper case letter 'Z'. Commented Mar 16, 2018 at 19:15
  • @NinaScholz Why ? I did a few tests and it works alright with the lowercase "z" ? Commented Mar 16, 2018 at 19:17
  • 2
    just according to the standard, it should work for comparison with small letter, too. Commented Mar 16, 2018 at 19:20

2 Answers 2

12

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".

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.