为什么是YYYY-MM-DD!= YYYY/MM/DD [英] Why is YYYY-MM-DD != YYYY/MM/DD

查看:54
本文介绍了为什么是YYYY-MM-DD!= YYYY/MM/DD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Chrome中,我们有些奇怪

In Chrome, we get some weirdness

> new Date("2014-01-01") - new Date("2014/01/01")
< 3600000

这是因为

new Date("2014-01-01")
Wed Jan 01 2014 01:00:00 GMT+0100 (CET)

同时

new Date("2014/01/01")
Wed Jan 01 2014 00:00:00 GMT+0100 (CET)

为什么'-'似乎增加了1个小时?

Why do the '-' seem to add 1 hour to the time?

推荐答案

我相信差异是由 Date.parse 将UTC添加到一个字符串而不是另一个字符串引起的,即:/在Date.parse()中不是合法的分隔符,这意味着在解析UTC时不会将其添加到时间中.由于'是合法的分隔符,因此将对其进行解析,然后将UTC添加到返回的时间中.

I believe that the difference is caused by Date.parse adding UTC to one string but not the other, namely: / is not a legal separator in Date.parse() which means that UTC isn't added to the time once it's parsed. Because ' is a legal separator, it is parsed and then UTC is added to the returned time.

Date.parse new Date()方法使用,并且其实现是特定于浏览器的,我很惊讶这种事情不会再出现了经常.

Date.parse is used by the new Date() method and its implementation is browser specific, I'm surprised this sort of thing doesn't come up more often.

Date.parse 的规范说:

The specification for Date.parse says:

根据字符串的内容,字符串可以解释为本地时间,UTC时间或其他时区中的时间.该函数首先尝试根据日期时间字符串格式(15.9.1.15)中调用的规则来解析字符串的格式.如果String不符合该格式,则该函数可能会退回到任何特定于实现的启发式或特定于实现的日期格式.

The String may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the String. The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

因此,我建议要么在解析之前手动添加时区,要么丢弃 new Date()返回的时间,但是这可能会导致午夜等问题.最安全的做法是看看是否可以从两个系统中以更具体的格式获取日期以及时区信息.

So I'd suggest either adding in a timezone manually before you parse, or discarding the time returned by new Date(), however that could lead to issues around midnight etc. The safest thing would be to see if you can get the date in a more specific format from both systems, with timezone information.

这篇关于为什么是YYYY-MM-DD!= YYYY/MM/DD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆