javascript Date跨时区问题

实际项目中,遇到使用Date获得的时间戳加上一天的毫秒数,然后调用getDate居然返回不对。

然后用户反馈不再国内。

在网上找到这篇文章:https://juejin.im/post/5d23ef766fb9a07ea5681378

说到Date的有下面这个问题:

new Date会自动变成本地时区

在js中,很多时候需要把日期字符串转换为一个 Date 对象。如果得到的日期字符串有时间还好办,如果就是一个"2019-10-10"这样的字符串呢?

大部分人可能什么都没想,直接就调用了 new Date(datestring)。可是事情没有想象中那么简单。让我们来对比一下:

var date1 = new Date('2019-10-10')
// Thu Oct 10 2019 08:00:00 GMT+0800 (中国标准时间)

var date2 = new Date('2019-10-10 00:00:00')
// Thu Oct 10 2019 00:00:00 GMT+0800 (中国标准时间)
复制代码

可以发现,直接输入日期,和输入日期+时间,得到的结果差了整整8个小时!

MDN中给出了详细的解释:

parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

简单翻译一下,直接给new Date传入'YYYY-MM-DD'这样的字符串,得到的是一个基于UTC时间的Date实例。前文有说过,UTC时间即是0时区的标准时间。

所以上面的代码例子中,date1 实例化时,内部先获取到了一个2019-10-10 00:00:00 GMT+00:00这样的时间,再被转为本地时区,就多了8个小时。

date2实例化时,2019-10-10 00:00:00被当做GMT +08:00的时区,所以得到的时间,就是0点。

这两种方式没有对与错之分,但是使用的时候需要十分注意。个人不建议使用new Date(YYYY-MM-DD)这样的方式。

说了一堆理论,到底哪些场景要注意问题呢?Show you the code:

// code is runningg on GMT +08:00
const d = new Date('2019-10-10');
const date = d.getDate();

// 10
// Looks good!


// code is runningg on GMT -10:00
const d = new Date('2019-10-10');
const date = d.getDate();

// 9
// Amazing?!
复制代码

总结上面的代码:在小于0时区的地方,直接用 new Date('YYYY-MM-DD') 这样的方式实例化日期并且获取日期,永远会少一天。但是使用 new Date('YYYY-MM-DD 00:00:00') 就不会。

使用 moment 可以轻松的解决上述问题:

moment('2019-10-10').toDate()
// Thu Oct 10 2019 00:00:00 GMT+0800 (中国标准时间)

moment('2019-10-10 00:00:00').toDate()
// Thu Oct 10 2019 00:00:00 GMT+0800 (中国标准时间)

处理日期操作还是建议使用专业的库。

发布了24 篇原创文章 · 获赞 3 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/u012787757/article/details/104171711