Wrong date from timestamp

后端 未结 4 1458
独厮守ぢ
独厮守ぢ 2021-01-21 18:20

I have a problem which can\'t solve by myself.

Here is timestamp 1308085200 taken from my website database. It represents 2011-06-15 12:00:00

Here is javascrip

相关标签:
4条回答
  • 2021-01-21 18:39

    JavaScript's Date::getMonth() returns a zero-based integer from 0 to 11 which is why your date is showing May instead of June.

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getMonth

    Update

    As for the time portion, this is what I get (AEST)

    var d = new Date(1308085200000); // Wed Jun 15 07:00:00 GMT+1000 (EST)
    d.toUTCString() // Tue, 14 Jun 2011 21:00:00 GMT
    d.getUTCFullYear() // 2011
    d.getUTCMonth() // 5
    d.getUTCDate() // 14
    d.getUTCHours() // 21
    d.getUTCMinutes() // 0
    d.getUTCSeconds() // 0
    

    Looks like your timestamp is actually not what you think it is.

    0 讨论(0)
  • 2021-01-21 18:43

    Well, JavaScript's getMonth() function sucks and starts with 0 for January. You have to add one.

    Maybe you want to use date js, since it fixes some of these problems.

    0 讨论(0)
  • 2021-01-21 18:47

    Try this:

     function timeConverter(createdAt) {
      var date = new Date(createdAt);
      date.toUTCString()
      var year = date.getUTCFullYear();
      var month = date.getUTCMonth()+1;
      var day = date.getUTCDate();
      return day+"-"+month+"-"+year;
    }
    
    0 讨论(0)
  • 2021-01-21 18:50

    The date and time can vary dependent on the timezone you're in. That's why in my zone (GMT+2000) new Date(1308085200*1000) displays Tue Jun 14 2011 23:00:00 GMT+0200 (W. Europe Daylight Time). Check this reference for everything you always wanted to know about dates in javascript

    Regarding formatting (leading zero's etc.), maybe this jsfiddle can help you?

    0 讨论(0)
提交回复
热议问题