为什么js会从一个特定格式的Date对象中减去一天?

Why does js subtract a day from a Date object with a certain format?

我以这种格式从数据库中获取日期:

yyyy-mm-dd

当我使用此字符串创建 javascript 日期对象时,它会在日期前一天构建。

您可以在控制台中进行测试:

var d = new Date("2015-02-01"); 
d

您将获得 1 月 31 日!我测试了很多理论,但 none 回答了这个问题。

我的结论是js是故意的。我曾尝试研究 'why' 但找不到解释。 为什么 js 以这种方式构建日期,但只能使用这种格式?有没有办法解决这个问题,或者我是否必须构建日期,然后将其设置为第二天?

PS:"How to change the format of the date from the db" 不是我要问的,这就是为什么我不在此处放置任何数据库信息的原因。

有些浏览器将部分日期字符串解析为 UTC,有些浏览器解析为本地时间,

所以当您阅读它时,本地化时间可能因浏览器而异

按时区偏移。

如果

您可以强制日期为 UTC 并添加本地偏移量

想保证本地时间:

1. set UTC time:    

var D= new Date("2015-02-01"+'T00:00:00Z');


2. adjust for local:

D.setMinutes(D.getMinutes()+D.getTimezoneOffset());

D 的值:(本地日期) 2015 年 2 月 1 日星期日 00:00:00 GMT-0500(东部标准时间)

偏移量将是本地时间。

Some differences between browsers when time zone is not specified in a parsed string:

(tested on Eastern Standard Time location)

(new Date("2015-02-01T00:00:00")).toUTCString();


Firefox 35: Sun, 01 Feb 2015 05:00:00 GMT

Chrome 40: Sun, 01 Feb 2015 00:00:00 GMT

Opera 27: Sun, 01 Feb 2015 00:00:00 GMT

IE 11: Sun, 01 Feb 2015 05:00:00 GMT

IE and Firefox set the Date as if it was local, Chrome and Opera as if it was UTC. 

在 javascript 中,日期对象在内部表示为自 1970 年 1 月 1 日以来的毫秒数 00:00:00 UTC。因此,与其将其视为正常意义上的 "date",不如 尝试将 Date 对象视为由整数 (无时区)表示的 "point in time" .

当使用字符串构建 Date 对象时,您实际上只是在调用 parse function. Most date time formats (including ISO 8601) 允许您降低日期字符串的精度。

For reduced precision, any number of values may be dropped from any of the date and time representations, but in the order from the least to the most significant.

例如2015-02-01 表示 2015 年 2 月 1 日.

这导致 javascript 进退两难,因为 Date 对象始终精确到毫秒。 Javascript 无法存储精度降低的日期,因为它只是自 1970 年 1 月 1 日以来的毫秒整数。因此,如果未指定,它会做下一个最好的事情,即假定午夜时间 (00:00:00),如果未指定,则为 UTC 时区。

所有有效的 javascript 实现应该给出相同的结果 for this:

var d = new Date("2015-02-01");
alert(d.getTime());

1422748800000

将日期输出到某些(通常不清楚的)调试器或使用 getter 方法时会出现 1 天后的问题,因为使用了本地时区。在浏览器中,这将是您的操作系统时区。 Greenwich Mean Time may see this problem because they have a negative UTC offset. Please note there are UTC equivalent functions 的 "west" 也使用 UTC 时区的任何人,如果您真的只对表示日期而不是时间点感兴趣。