Chrome和其他浏览器中的javascript date.parse差异 [英] javascript date.parse difference in chrome and other browsers

查看:138
本文介绍了Chrome和其他浏览器中的javascript date.parse差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从graph.facebook API获取了一个日期字符串2011-11-24T09:00:27 + 0000。

I have a date string "2011-11-24T09:00:27+0000" fetched from the graph.facebook API.

当我运行时

var timestamp = Date.parse(facebookDate);

in chrome。我得到一个与日期有关的时间戳!完美!

in chrome. I get a timestamp that relates to the date! perfect!

但在其他主要浏览器中......我得到NaN!!! ?

But in EVERY other major browser... I get "NaN" !!! ?

当然所有这些浏览器都使用相同的javascript解析函数吗?

Surely all these browsers use the same javascript parse function right?

任何人都可以解释为什么同样的javascript函数给出不同的结果?

Can anybody explain why the same javascript function give different results?

也可以有人告诉我如何解决这个问题...

And can anybody also tell me how to fix this issue...

谢谢提前

Alex

推荐答案

这是针对Firefox和IE / Safari(在 JavaScript:哪些浏览器支持使用Date.parse解析ISO-8601日期字符串
):

Here is a fix for Firefox and IE/Safari (with the help from JavaScript: Which browsers support parsing of ISO-8601 Date String with Date.parse ) :

DEMO

var noOffset = function(s) {
  var day= s.slice(0,-5).split(/\D/).map(function(itm){
    return parseInt(itm, 10) || 0;
  });
  day[1]-= 1;
  day= new Date(Date.UTC.apply(Date, day));  
  var offsetString = s.slice(-5)
  var offset = parseInt(offsetString,10)/100;
  if (offsetString.slice(0,1)=="+") offset*=-1;
  day.setHours(day.getHours()+offset);
  return day.getTime();
}

来自 MDN

JavaScript 1.8.5 note

JavaScript 1.8.5 note

现在也可以解析ISO 8601格式化日期字符串的子集。

A subset of ISO 8601 formatted date strings can now also be parsed.

或者,日期/时间字符串可能在ISO 8601中格式。从JavaScript 1.8.5 / Firefox 4开始,支持ISO 8601的子集。例如,可以传递和解析2011-10-10(仅限日期)或2011-10-10T14:48:00(日期和时间)。尚未支持ISO日期中的时区,例如2011- 10-10T14:48:00 + 0200(带时区)尚未给出预期的结果。

Alternatively, the date/time string may be in ISO 8601 format. Starting with JavaScript 1.8.5 / Firefox 4, a subset of ISO 8601 is supported. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00 (date and time) can be passed and parsed. Timezones in ISO dates are not yet supported, so e.g. "2011-10-10T14:48:00+0200" (with timezone) does not give the intended result yet.

这篇关于Chrome和其他浏览器中的javascript date.parse差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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