创建新的日期对象时出现不一致 [英] Inconsistencies when creating new date objects
问题描述
我正在用javascript创建新的日期对象,并看到一些不一致之处,这取决于我是否使用dateString参数还是年/月/日整数参数。
I am creating new date objects in javascript and seeing some inconsistencies depending on whether I use the dateString parameter vs the year/month/day integer parameters.
例如:
var dt1 = new Date(1979,3,5);
var dt2 = new Date('1979-04-05');
dt1被分配了值:1979年4月5日星期四GMT-0500(中央夏令时)
dt1 is assigned the value: Thu Apr 05 1979 00:00:00 GMT-0500 (Central Daylight Time)
dt2分配了值:1979年4月4日星期三19:00:00 GMT-0500(中央夏令时)
dt2 is assigned the value: Wed Apr 04 1979 19:00:00 GMT-0500 (Central Daylight Time)
有人可以解释这种行为吗?第二个示例(dt2)恰好是Chrome从input [type = date]元素返回选定日期的格式,这就是为什么我试图弄清楚这一点的原因。
Can someone explain this behavior? The second example (dt2) happens to be the format that Chrome is returning a selected date from input[type=date] elements which is why I'm trying to figure this out.
推荐答案
看起来'1979-04-05'
的形式被解释为UTC日期(然后是UTC日期显示时转换为本地时间)。 new Date(1979,3,5);
的形式被解释为本地时间。您可以使用 Date.UTC
强制使用3参数形式的UTC时间(请参阅文档)。
It looks like the form '1979-04-05'
is interpreted as a UTC date (and then that UTC date is converted to local time when displayed). The form new Date(1979,3,5);
is interpreted as local time. You can use Date.UTC
to force UTC time for the 3-argument form (see docs).
Date
的解析(尤其是时区处理)通常在浏览器中并不统一,最好不要依赖它-尽可能使用UTC,或使用单独的库,例如 Date.js 或 moment.js 。
Date
parsing (and timezone handling in particular) is generally not uniform across browsers, and it's better not to depend on it - use UTC whenever possible, or use a separate library like Date.js or moment.js.
这篇关于创建新的日期对象时出现不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!