Is direct comparison of Javascript ISO Date Strings safe?

我们两清 提交于 2021-01-02 06:43:48

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/49327580/is-direct-comparison-of-javascript-iso-date-strings-safe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!