How do I format a timestamp in Javascript to display it in graphs? UTC is fine

后端 未结 3 1267
-上瘾入骨i
-上瘾入骨i 2021-02-13 02:19

Basically, I receive raw timestamps and I need to format them into HH:MM:SS format.

3条回答
  •  鱼传尺愫
    2021-02-13 02:57

    I'll go with the assumption that you mean Unix timestamps:

    var formatTime = function(unixTimestamp) {
        var dt = new Date(unixTimestamp * 1000);
    
        var hours = dt.getHours();
        var minutes = dt.getMinutes();
        var seconds = dt.getSeconds();
    
        // the above dt.get...() functions return a single digit
        // so I prepend the zero here when needed
        if (hours < 10) 
         hours = '0' + hours;
    
        if (minutes < 10) 
         minutes = '0' + minutes;
    
        if (seconds < 10) 
         seconds = '0' + seconds;
    
        return hours + ":" + minutes + ":" + seconds;
    }       
    
    var formattedTime = formatTime(1266272460);
    document.write(formattedTime);
    

提交回复
热议问题