javascript date object issue in Safari and IE

后端 未结 5 1689
广开言路
广开言路 2020-12-16 03:02

I am taking a date from a JSON object in the format of 2012-12-31 and trying to convert it into friendly values and output it.

    var redeemableDate = item.         


        
5条回答
  •  死守一世寂寞
    2020-12-16 03:46

    You're better off parsing the date string yourself:

    function dateFromISO( str ) {
      var d = null;
      str.replace(/^(\d\d\d\d)-(\d\d)-(\d\d)$/, function(_, y, m, d) {
        d = new Date(parseInt(y, 10), parseInt(m, 10) - 1, parseInt(d, 10));
      });
      return d;
    }
    
    redeemableDate = dateFromISO( redeemableDate );
    

    Even if the other browsers liked those date strings, you'd have the problem of them always being interpreted as UTC. For me, for example, when I pass that string "2012-12-31" to Firefox, it tells me that the date is 30 Dec 2012, because I'm 6 hours behind UTC. In other words, "2012-12-31" is interpreted as midnight of that date, UTC time. Assuming you want everybody in the world to see the right date, if you construct the Date object with numbers it's assumed to be local time at the client.

提交回复
热议问题