简体   繁体   English

Javascript新日期对待不同的日期风格有不同的看法?

[英]Javascript new date treats differently towards different date style?

I tested the following code in firefox scratchpad and got interesting result? 我在firefox scratchpad中测试了下面的代码并获得了有趣的结果?

var date=new Date("2012-05-12");
var date2 = new Date("05/12/2012");
date;
/*
Fri May 11 2012 17:00:00 GMT-0700 (Pacific Daylight Time)
*/
date2;
/*
Sat May 12 2012 00:00:00 GMT-0700 (Pacific Daylight Time)
*/

Two dates are different. 两个日期不同。 Apparently this is due to the timezone issue. 显然这是由于时区问题。 What I want is date2 result. 我想要的是date2结果。 How can I make js engine correctly treats the ISO date style? 如何使js引擎正确处理ISO日期样式?

I think the issue is that the string "2012-05-12" is taken to be an ISO 8601 date, while "05/12/2012" is an RFC 2822 date. 我认为问题是字符串“2012-05-12”被认为是ISO 8601日期,而“05/12/2012”是RFC 2822日期。 In the ISO format, the lack of a timezone implies UTC. 在ISO格式中,缺少时区意味着UTC。 At midnight on the morning off May 12, in California (or wherever you are) it's 7 PM the previous evening. 5月12日早上午夜,在加利福尼亚(或任何地方),前一天晚上7点。

The RFC date without a time zone, however, is parsed under the assumption that you want the timestamp for midnight in your local timezone. 但是,在没有时区的RFC日期的基础上,假设您希望在当地时区中设置午夜时间戳。 (Well, not necessarily your timezone; the timezone of the computer where your JavaScript runs :-) (好吧,不一定是你的时区;运行JavaScript的计算机的时区:-)

You can see the difference if you pass those strings to Date.parse() . 如果将这些字符串传递给Date.parse()则可以看到差异。

The RFC date format can include an explicit time zone, but the ISO format cannot. RFC日期格式可以包含显式时区,但ISO格式不能。 (Well, it can, but browsers don't pay attention, and apparently IE doesn't handle those at all.) (嗯,它可以,但浏览器不注意,显然IE根本不处理这些。)

edit — here's a simple (dumb; no error checking) function that'll give you a date from that 3-part ISO form: 编辑 - 这是一个简单的(哑;没有错误检查)功能,它会给你一个3部分ISO表格的日期:

function isoDate( str ) {
  var rv = null;
  str.replace(/^(\d\d\d\d)-(\d\d)-(\d\d)$/, function(_, yr, mn, dy) {
    rv = new Date(parseInt(yr, 10), parseInt(mn, 10) - 1, parseInt(dy, 10));
  });
  return rv;
}

By the standard, with Date() , you can parse ISO dates or dates in an implementation-dependent format, in an an implementation-dependent manner. 根据标准,使用Date() ,您可以依赖于实现的方式以依赖于实现的格式解析ISO日期或日期。 To get anything more reliable, use a suitable library that can parse dates in some known formats. 要获得更可靠的信息,请使用可以解析某些已知格式的日期的合适库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM