Convert a Unix timestamp to time in JavaScript

前端 未结 29 2156
渐次进展
渐次进展 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:39

    You can use the following function to convert your timestamp to HH:MM:SS format :

    var convertTime = function(timestamp, separator) {
        var pad = function(input) {return input < 10 ? "0" + input : input;};
        var date = timestamp ? new Date(timestamp * 1000) : new Date();
        return [
            pad(date.getHours()),
            pad(date.getMinutes()),
            pad(date.getSeconds())
        ].join(typeof separator !== 'undefined' ?  separator : ':' );
    }
    

    Without passing a separator, it uses : as the (default) separator :

    time = convertTime(1061351153); // --> OUTPUT = 05:45:53
    

    If you want to use / as a separator, just pass it as the second parameter:

    time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55
    

    Demo

    var convertTime = function(timestamp, separator) {
        var pad = function(input) {return input < 10 ? "0" + input : input;};
        var date = timestamp ? new Date(timestamp * 1000) : new Date();
        return [
            pad(date.getHours()),
            pad(date.getMinutes()),
            pad(date.getSeconds())
        ].join(typeof separator !== 'undefined' ?  separator : ':' );
    }
    
    document.body.innerHTML = '
    ' + JSON.stringify({
        920535115 : convertTime(920535115, '/'),
        1061351153 : convertTime(1061351153, ':'),
        1435651350 : convertTime(1435651350, '-'),
        1487938926 : convertTime(1487938926),
        1555135551 : convertTime(1555135551, '.')
    }, null, '\t') +  '
    ';

    See also this Fiddle.

提交回复
热议问题