IE 7中的Javascript Date功能问题返回NaN [英] Problem with Javascript Date function in IE 7, returns NaN

查看:127
本文介绍了IE 7中的Javascript Date功能问题返回NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个twitter feed,我创建一个新的日期obj,所以我可以格式化日期到我的喜好。

I have a twitter feed and I create a new date obj so I can format the date to my liking.

var created = new Date(this.created_at)适用于Firefox和chrome,但不在IE7中。通过新的Date()功能,我似乎无法传递日期。它只返回undefined和NaN。

var created = new Date(this.created_at) works in firefox and chrome but not in IE7. I seem to be having trouble passing the date through the new Date() function. It just returns undefined and NaN.

这是代码。如果你尝试测试它不要忘记包括jquery。谢谢。

Here is the code. If you try to test it out don't forget to include jquery. Thank you.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Twitter Test</title>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" >

$(function(){
$.getJSON("http://twitter.com/statuses/user_timeline/google.json?count=1&callback=?", function(data){
    $.each(data, function(){
        var created = new Date(this.created_at)
        $("<div></div>").append("<ul><li>Unformatted: " + this.created_at + "</li><li>Formatted: " + created + "</li></ul>").appendTo("body")
    });

})  

})

</script>
</head>

<body>
</body>
</html>


推荐答案

您需要确保日期被解析作为UTC,因为否则javascript会将其解释为当地时区的日期。

You'll want to make sure the date is parsed as UTC, because otherwise javascript will interpret it as a date in your local timezone.

日期如下所示: Tue Jul 13 23:18 :36 +0000 2010

您可以这样解析:

function parseDate(str) {
  var v=str.split(' ');
  return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
} 

哪个将在当地时区提供正确的日期/时间,例如: Tue Jul 13 2010 19:18:36 GMT-0400(EDT)

Which will give the correct date/time in the local timezone, for example: Tue Jul 13 2010 19:18:36 GMT-0400 (EDT)

所以应该让你的代码看起来如下所示:

So that should leave your code looking something like this:

$(function(){
  $.getJSON("http://twitter.com/statuses/user_timeline/google.json?count=1&callback=?", function(data){
    $.each(data, function(){
      var created = parseDate(this.created_at);
      $("<div></div>").append("<ul><li>Unformatted: " + this.created_at + "</li><li>Formatted: " + created + "</li></ul>").appendTo("body");
    });
  });
  function parseDate(str) {
    var v=str.split(' ');
    return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
  } 
});

这篇关于IE 7中的Javascript Date功能问题返回NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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