Timestamp to human readable format

前端 未结 5 1608
面向向阳花
面向向阳花 2020-12-04 10:43

Well I have a strange problem while convert from unix timestamp to human representation using javascript

Here is timestamp

1301090400
相关标签:
5条回答
  • 2020-12-04 11:02
    var newDate = new Date();
    newDate.setTime(unixtime*1000);
    dateString = newDate.toUTCString();
    

    Where unixtime is the time returned by your sql db. Here is a fiddle if it helps.

    For example, using it for the current time:

    document.write( new Date().toUTCString() );

    0 讨论(0)
  • 2020-12-04 11:02

    use Date.prototype.toLocaleTimeString() as documented here

    please note the locale example en-US in the url.

    0 讨论(0)
  • 2020-12-04 11:08

    getDay() returns the day of the week. To get the date, use date.getDate(). getMonth() retrieves the month, but month is zero based, so using getMonth()+1 should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC to the methods (e.g. date.getUTCFullYear(), date.getUTCHours())

    var timestamp = 1301090400,
    date = new Date(timestamp * 1000),
    datevalues = [
       date.getFullYear(),
       date.getMonth()+1,
       date.getDate(),
       date.getHours(),
       date.getMinutes(),
       date.getSeconds(),
    ];
    alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]
    
    0 讨论(0)
  • 2020-12-04 11:08

    Hours, minutes and seconds depend on the time zone of your operating system. In GMT (UST) it's 22:00:00 but in different timezones it can be anything. So add the timezone offset to the time to create the GMT date:

    var d = new Date();
    date = new Date(timestamp*1000 + d.getTimezoneOffset() * 60000)
    
    0 讨论(0)
  • 2020-12-04 11:25

    here is kooilnc's answer w/ padded 0's

    function getFormattedDate() {
        var date = new Date();
    
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var min = date.getMinutes();
        var sec = date.getSeconds();
    
        month = (month < 10 ? "0" : "") + month;
        day = (day < 10 ? "0" : "") + day;
        hour = (hour < 10 ? "0" : "") + hour;
        min = (min < 10 ? "0" : "") + min;
        sec = (sec < 10 ? "0" : "") + sec;
    
        var str = date.getFullYear() + "-" + month + "-" + day + "_" +  hour + ":" + min + ":" + sec;
    
        /*alert(str);*/
    
        return str;
    }
    
    0 讨论(0)
提交回复
热议问题