Inconsistencies when creating new date objects

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.

Here's an example:

var dt1 = new Date(1979,3,5);
var dt2 = new Date('1979-04-05');

jsFiddle with example

dt1 is assigned the value: Thu Apr 05 1979 00:00:00 GMT-0500 (Central Daylight Time)

dt2 is assigned the value: Wed Apr 04 1979 19:00:00 GMT-0500 (Central Daylight Time)

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.


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

链接地址: http://www.djcxy.com/p/18640.html

上一篇: java.text.Parseexception,位置0处的不可分段日期? Android的

下一篇: 创建新日期对象时的不一致