Convert seconds to HH-MM-SS with JavaScript?

前端 未结 30 2051
南旧
南旧 2020-11-22 10:05

How can I convert seconds to an HH-MM-SS string using JavaScript?

相关标签:
30条回答
  • 2020-11-22 10:33

    For anyone using AngularJS, a simple solution is to filter the value with the date API, which converts milliseconds to a string based on the requested format. Example:

    <div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>
    

    Note that this expects milliseconds, so you may want to multiply timeRemaining by 1000 if you are converting from seconds (as the original question was formulated).

    0 讨论(0)
  • 2020-11-22 10:34
    function formatSeconds(seconds)
    {
        var date = new Date(1970,0,1);
        date.setSeconds(seconds);
        return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
    }
    
    0 讨论(0)
  • 2020-11-22 10:34

    Easy to follow version for noobies:

     var totalNumberOfSeconds = YOURNUMBEROFSECONDS;
     var hours = parseInt( totalNumberOfSeconds / 3600 );
     var minutes = parseInt( (totalNumberOfSeconds - (hours * 3600)) / 60 );
     var seconds = Math.floor((totalNumberOfSeconds - ((hours * 3600) + (minutes * 60))));
     var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
     console.log(result);
    
    0 讨论(0)
  • 2020-11-22 10:35

    new Date().toString().split(" ")[4];

    result 15:08:03

    0 讨论(0)
  • 2020-11-22 10:35
    String.prototype.toHHMMSS = function () {
        var sec_num = parseInt(this, 10); // don't forget the second param
        var hours   = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);
    
        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        return hours+':'+minutes+':'+seconds;
    }
    

    Usage Example

    alert("186".toHHMMSS());
    
    0 讨论(0)
  • I've used this code before to create a simple timespan object:

    function TimeSpan(time) {
    this.hours = 0;
    this.minutes = 0;
    this.seconds = 0;
    
    while(time >= 3600)
    {
        this.hours++;
        time -= 3600;
    }
    
    while(time >= 60)
    {
        this.minutes++;
        time -= 60;
    }
    
    this.seconds = time;
    }
    
    var timespan = new Timespan(3662);
    
    0 讨论(0)
提交回复
热议问题