Different params given to new Date lead to different results
是什么原因导致了这一问题呢?MDN中已经明确说明了:
单独使用一个日期,而不加任何别的参数,会被认为是UTC时间。
不清楚协调时间UTC、格林尼治时间GMT、夏令时 DST 的同学,可以参考下面的文章:
- [The Difference Between GMT and UTC](https://www.timeanddate.com/time/gmt-utc-time.html)
- [GMT、UTC与24时区 等时间概念](https://blog.csdn.net/webcainiao/article/details/4018761)
事实上大家也不用关心 GMT,二者在js,或者说浏览器中,差别不是太大
- The JavaScript Date object supports a number of UTC (universal) methods, as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. The local time is the time known to the computer where JavaScript is executed.
也就是说,下列代码是等同的:(P.S. new Date()的返回值,是按照本地时间进行展示的)
new Date("2018-11-19")
// Sun Nov 18 2018 16:00:00 GMT-0800 (北美太平洋标准时间)
new Date('Mon Nov 19 2018 00:00:00 GMT+0000')
// Sun Nov 18 2018 16:00:00 GMT-0800 (北美太平洋标准时间)
当我们在使用 new Date('2018-11-19') 创建一个date对象时,实际上就是在创建一个时区为 GMT+0,时间是2018-11-19 00:00:00的date对象。格林尼治的凌晨时分,对应到西八区,自然就是2018-11-18 16:00:00.也就出现了上述 HR 看到的日期少一天的问题。
Conclusion
尽量避免 new Date('yyyy-mm-dd') 的用法
如果需要创建一个日期对象,且希望不同时区下创建的该对象,都能展示为同一天,尽量加上 00:00:00 ,或者使用 new Date(y, [m, [d, [...]]])、 moment("2018-11-19").toDate()