带有字符串参数的javascript新日期的日期错误 [英] javascript new Date with string param has wrong date

查看:52
本文介绍了带有字符串参数的javascript新日期的日期错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据字符串创建新日期

I am creating a new date from string

var s = "2017-12-06"
var dt = new Date(s)
console.log(dt) // outputs Tue Dec 05 2017 19:00:00 GMT-0500 (EST)

我缺少什么?

推荐答案

Date.toString()的格式在您当地的时区,但是由于您已传递ISO-8601字符串,因此该值被解析为 ,就像UTC一样。

Date.toString() is formatted in your local time zone, but because you've passed in an ISO-8601 string, the value is parsed as if it's UTC.

来自 Date.parse()文档(因为 Date(String)构造函数是记录的行为类似于 Date.parse ):

From the Date.parse() documentation (as the Date(String) constructor is documented to behave like Date.parse):


日期时间字符串可能是以简化的ISO 8601格式。例如,可以传递和解析 2011-10-10(日期)或 2011-10-10T14:48:00(日期和时间)。如果字符串仅是ISO 8601日期,则UTC时区用于解释参数。如果字符串是ISO 8601格式的日期和时间,则将其视为本地字符串。

The date time string may be in a simplified ISO 8601 format. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can be passed and parsed. Where the string is ISO 8601 date only, the UTC time zone is used to interpret arguments. If the string is date and time in ISO 8601 format, it will be treated as local.

所以您最终会得到一个日期相当于2017-12-06T00:00:00Z。但是 Date.toString()会向您显示当前时区中的该时刻-如果您位于America / New_York或类似的时区,则要晚5小时当时的UTC,这意味着它将在12月5日晚上7点打印。

So you'll end up with a Date which is equivalent to 2017-12-06T00:00:00Z. But Date.toString() shows you that instant in time in your current time zone - and if you're in America/New_York or a similar time zone which is 5 hours behind UTC at that moment in time, that means it'll print December 5th at 7pm.

这篇关于带有字符串参数的javascript新日期的日期错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆