IE 7 中 Javascript 日期函数的问题,返回 NaN [英] Problem with Javascript Date function in IE 7, returns NaN

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

问题描述

我有一个 twitter 提要,我创建了一个新的日期对象,这样我就可以根据自己的喜好格式化日期.

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.我似乎无法通过 new 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 日期函数的问题,返回 NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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