Problem with Javascript Date function in IE 7, returns NaN

前端 未结 3 1142
我寻月下人不归
我寻月下人不归 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:36

    Here is what I made to correct this!

    $tweetList.append('<p><span class="twitterdate">' + parseTwitterDate(item.created_at) + location + '</span></p>');
    
    var month=new Array();
    month[0]="January";
    month[1]="February";
    month[2]="March";
    month[3]="April";
    month[4]="May";
    month[5]="June";
    month[6]="July";
    month[7]="August";
    month[8]="September";
    month[9]="October";
    month[10]="November";
    month[11]="December";
    
    function parseTwitterDate($stamp) {
        var v=$stamp.split(' ');
        var date = new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
        var hour = date.getHours();
        var ampm = hour<12 ? ' AM' : ' PM';
        return date.getHours() +':'+ date.getMinutes() +' '+ ampm +' '+ date.getDate() +' '+ month[date.getMonth()] +' '+ date.getFullYear();
    }
    

    And this give me "19:38 PM 23 April 2012" on Chrome, IE and Firefox.

    0 讨论(0)
  • 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);
          $("<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"));
      } 
    });
    
    0 讨论(0)
  • 2020-12-10 02:56

    I've found the jQuery Globalization Plugin date parsing to work best. Other methods had cross-browser issues and stuff like date.js had not been updated in quite a while.

    You also don't need a datePicker on the page. You can just call something similar to the example given in the docs:

    $.parseDate('yy-mm-dd', '2007-01-26');
    
    0 讨论(0)
提交回复
热议问题