Convert a Unix timestamp to time in JavaScript

前端 未结 29 2079
渐次进展
渐次进展 2020-11-21 04:57

I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?

For example, in HH/MM/

相关标签:
29条回答
  • 2020-11-21 05:28

    Shortest

    (new Date(ts*1000)+'').slice(16,24)
    

    let ts = 1549312452;
    let time = (new Date(ts*1000)+'').slice(16,24);
    
    console.log(time);

    0 讨论(0)
  • 2020-11-21 05:29

    I'm partial to Jacob Wright's Date.format() library, which implements JavaScript date formatting in the style of PHP's date() function.

    new Date(unix_timestamp * 1000).format('h:i:s')
    
    0 讨论(0)
  • 2020-11-21 05:31

    Using Moment.js, you can get time and date like this:

    var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");
    

    And you can get only time using this:

    var timeString = moment(1439198499).format("HH:mm:ss");
    
    0 讨论(0)
  • 2020-11-21 05:32
    function getDateTime(unixTimeStamp) {
    
        var d = new Date(unixTimeStamp);
        var h = (d.getHours().toString().length == 1) ? ('0' + d.getHours()) : d.getHours();
        var m = (d.getMinutes().toString().length == 1) ? ('0' + d.getMinutes()) : d.getMinutes();
        var s = (d.getSeconds().toString().length == 1) ? ('0' + d.getSeconds()) : d.getSeconds();
    
        var time = h + '/' + m + '/' + s;
    
        return time;
    }
    
    var myTime = getDateTime(1435986900000);
    console.log(myTime); // output 01/15/00
    
    0 讨论(0)
  • 2020-11-21 05:33

    UNIX timestamp is number of seconds since 00:00:00 UTC on January 1, 1970 (according to Wikipedia).

    Argument of Date object in Javascript is number of miliseconds since 00:00:00 UTC on January 1, 1970 (according to W3Schools Javascript documentation).

    See code below for example:

        function tm(unix_tm) {
            var dt = new Date(unix_tm*1000);
            document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');
    
        }
    
    tm(60);
    tm(86400);
    

    gives:

    1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
    1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)
    
    0 讨论(0)
  • 2020-11-21 05:33

    Pay attention to the zero problem with some of the answers. For example, the timestamp 1439329773 would be mistakenly converted to 12/08/2015 0:49.

    I would suggest on using the following to overcome this issue:

    var timestamp = 1439329773; // replace your timestamp
    var date = new Date(timestamp * 1000);
    var formattedDate = ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
    console.log(formattedDate);
    

    Now results in:

    12/08/2015 00:49
    
    0 讨论(0)
提交回复
热议问题