使用当地时区分析YYYY-MM-DD日期 [英] Parse YYYY-MM-DD dates using the local timezone

查看:139
本文介绍了使用当地时区分析YYYY-MM-DD日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中,如果我将日期指定为 MM / DD / YYYY ,我可以使用 new Date()将其解析为本地时区:

 >>>新日期('01 / 01/1970')
日期{Thu Jan 01 1970 00:00:00 GMT-0500(EST)}

但是,如果我将日期指定为 YYYY-MM-DD ,则假定我在UTC时区:

 >>>新日期('1970-01-01')
日期{Wed Dec 31 1969 19:00:00 GMT-0500(EST)}

解析YYYY-MM-DD日期时,有一种简单的方法来告诉日期解析器使用本地时区吗?或者我需要使用 .replace(/ ^(\d {4}) - (\d {2}) - (\d {2})$ /,'$ 2 / $ 3 / code)来修复它首先?

解决方案

Date.parse的行为如下: p>

http ://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2


函数首先尝试根据日期时间字符串格式(15.9.1.15)中调用的规则解析String的格式。如果String不符合该格式,该函数可能会退回到任何实现特定的启发式或实现特定日期格式。


http://www.ecma-international.org/ecma- 262 / 5.1 /#sec-15.9.1.15


ECMAScript根据简化定义日期时间的字符串交换格式的ISO 8601扩展格式。格式如下:YYYY-MM-DDTHH:mm:ss.sssZ



Z是指定为Z(UTC)或 +或 - 后跟一个时间表达式HH:mm



缺席时区偏移量的值为Z。


所以在第一种情况下,由于它不适合日期时间字符串格式,实现特定的解析将生效(这恰好是基于本地时间) 。在第二种情况下,它符合DTSF,因此它被解析为如果时区未指定(应为UTC),因此差异


In javascript, if I specify the date as MM/DD/YYYY, I can use new Date() to parse it as the local timezone:

>>> new Date('01/01/1970')
Date {Thu Jan 01 1970 00:00:00 GMT-0500 (EST)}

However, if I specify the date as YYYY-MM-DD, it assumes that I'm giving the date in the UTC timezone:

>>> new Date('1970-01-01')
Date {Wed Dec 31 1969 19:00:00 GMT-0500 (EST)}

Is there an easy way to tell the date parser to use the local timezone when parsing 'YYYY-MM-DD' dates? Or do I need to use .replace(/^(\d{4})-(\d{2})-(\d{2})$/, '$2/$3/$1') to fix it first?

解决方案

Date.parse behaves as follows:

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2

The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

Z is the time zone offset specified as "Z" (for UTC) or either "+" or "-" followed by a time expression HH:mm

The value of an absent time zone offset is "Z".

So in the first case, since it doesn't fit the Date Time String Format, the implementation-specific parse takes effect (which happens to be based on local time). In the second case, it does fit the DTSF, so it is parsed as if the time zone was unspecified (which is supposed to be UTC), hence the disparity

这篇关于使用当地时区分析YYYY-MM-DD日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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