Why does new Date('2018-12-29') return December 28? [duplicate]

问题: This question already has an answer here: Why does Date.parse give incorrect results? 11 answers If right now in my devtools console I type: new...

问题:

This question already has an answer here:

If right now in my devtools console I type:

new Date('2018-12-29')

It returns:

Fri Dec 28 2018 16:00:00 GMT-0800 (Pacific Standard Time)

Why does that happen and what's the right way to fix this?

Does this have to do with timezones? How can I make sure it works properly for all my users?


回答1:

From the JavaScript Date docs:

If at least two arguments are supplied, missing arguments are either set to 1 (if the day is missing) or 0 for all others

Also from the dateString parameter description in the docs:

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

Since you are passing an ISO 8601 format string and there are no time elements in your date string, it is filling those parameters with zeros and creating a date object in UTC like 2018-12-29T00:00:00.000Z and then the browser converts it to your local time, which in your case is 8 hours behind and on the previous day in the Pacific Time Zone.


回答2:

Notice that Eastern Daylight Time is -4 hours and that the hours on the date you're getting back are 20.

20h + 4h = 24h

which is midnight of 2018-12-29.

You're getting the right date, you just never specified the correct time zone.

If you need to access the date values, you can use getUTCDate() or any of the other getUTC*() functions:

var d, days;
d = new Date('2018-12-29');
days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'];
console.log(days[d.getUTCDay()]);
  • 发表于 2018-12-31 19:28
  • 阅读 ( 149 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除