Problem with Javascript Date function in IE 7, returns NaN

前端 未结 3 1141
我寻月下人不归
我寻月下人不归 2020-12-10 02:33

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) works in firefox and c

3条回答
  •  失恋的感觉
    2020-12-10 02:39

    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.

    The date looks like this: Tue Jul 13 23:18:36 +0000 2010

    You can parse it like this:

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

    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);
          $("
    ").append("
    • Unformatted: " + this.created_at + "
    • Formatted: " + created + "
    ").appendTo("body"); }); }); function parseDate(str) { var v=str.split(' '); return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC")); } });

提交回复
热议问题