Convert seconds to HH-MM-SS with JavaScript?

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

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

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

    You can also use below code:

    int ss = nDur%60;
    nDur   = nDur/60;
    int mm = nDur%60;
    int hh = nDur/60;
    
    0 讨论(0)
  • 2020-11-22 10:29
    var  timeInSec = "661"; //even it can be string
    
    String.prototype.toHHMMSS = function () { 
       /* extend the String by using prototypical inheritance */
        var seconds = parseInt(this, 10); // don't forget the second param
        var hours   = Math.floor(seconds / 3600);
        var minutes = Math.floor((seconds - (hours * 3600)) / 60);
        seconds = seconds - (hours * 3600) - (minutes * 60);
    
        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        var time    = hours+':'+minutes+':'+seconds;
        return time;
    }
    
    alert("5678".toHHMMSS());   // "01:34:38"
    console.log(timeInSec.toHHMMSS());   //"00:11:01"
    

    we can make this function lot shorter and crisp but that decreases the readability, so we will write it as simple as possible and as stable as possible.

    or you can check this working here:

    0 讨论(0)
  • 2020-11-22 10:30

    below is the given code which will convert seconds into hh-mm-ss format:

    var measuredTime = new Date(null);
    measuredTime.setSeconds(4995); // specify value of SECONDS
    var MHSTime = measuredTime.toISOString().substr(11, 8);
    

    Get alternative method from Convert seconds to HH-MM-SS format in JavaScript

    0 讨论(0)
  • 2020-11-22 10:32

    I know this is kinda old, but...

    ES2015:

    var toHHMMSS = (secs) => {
        var sec_num = parseInt(secs, 10)
        var hours   = Math.floor(sec_num / 3600)
        var minutes = Math.floor(sec_num / 60) % 60
        var seconds = sec_num % 60
    
        return [hours,minutes,seconds]
            .map(v => v < 10 ? "0" + v : v)
            .filter((v,i) => v !== "00" || i > 0)
            .join(":")
    }
    

    It will output:

    toHHMMSS(129600) // 36:00:00
    toHHMMSS(13545) // 03:45:45
    toHHMMSS(180) // 03:00
    toHHMMSS(18) // 00:18
    
    0 讨论(0)
  • 2020-11-22 10:32

    For the special case of HH:MM:SS.MS (eq: "00:04:33.637") as used by FFMPEG to specify milliseconds.

    [-][HH:]MM:SS[.m...]

    HH expresses the number of hours, MM the number of minutes for a maximum of 2 digits, and SS the number of seconds for a maximum of 2 digits. The m at the end expresses decimal value for SS.

    /* HH:MM:SS.MS to (FLOAT)seconds ---------------*/
    function timerToSec(timer){
       let vtimer = timer.split(":")
       let vhours = +vtimer[0]
       let vminutes = +vtimer[1]
       let vseconds = parseFloat(vtimer[2])
       return vhours * 3600 + vminutes * 60 + vseconds
    }
    
    /* Seconds to (STRING)HH:MM:SS.MS --------------*/
    function secToTimer(sec){
      let o = new Date(0)
      let p =  new Date(sec*1000)  
      return new Date(p.getTime()-o.getTime())
        .toISOString()
        .split("T")[1]
        .split("Z")[0]
    }
    
    /* Example: 7hours, 4 minutes, 33 seconds and 637 milliseconds */
    const t = "07:04:33.637"
    console.log(
      t + " => " +
      timerToSec(t) +
      "s"
    )
    
    /* Test: 25473 seconds and 637 milliseconds */
    const s = 25473.637 // "25473.637"
    console.log(
      s + "s => " + 
      secToTimer(s)
    )

    Example usage, a milliseconds transport timer:

    /* Seconds to (STRING)HH:MM:SS.MS --------------*/
    function secToTimer(sec){
      let o = new Date(0)
      let p =  new Date(sec*1000)  
      return new Date(p.getTime()-o.getTime())
        .toISOString()
        .split("T")[1]
        .split("Z")[0]
    }
    
    let job, origin = new Date().getTime()
    const timer = () => {
      job = requestAnimationFrame(timer)
      OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000)
    }
    
    requestAnimationFrame(timer)
    span {font-size:4rem}
    <span id="OUT"></span>
    <br>
    <button onclick="origin = new Date().getTime()">RESET</button>
    <button onclick="requestAnimationFrame(timer)">RESTART</button>
    <button onclick="cancelAnimationFrame(job)">STOP</button>

    Example usage, binded to a media element

    /* Seconds to (STRING)HH:MM:SS.MS --------------*/
    function secToTimer(sec){
      let o = new Date(0)
      let p =  new Date(sec*1000)  
      return new Date(p.getTime()-o.getTime())
        .toISOString()
        .split("T")[1]
        .split("Z")[0]
    }
    
    VIDEO.addEventListener("timeupdate", function(e){
      OUT.textContent = secToTimer(e.target.currentTime)
    }, false)
    span {font-size:4rem}
    <span id="OUT"></span><br>
    <video id="VIDEO" width="400" controls autoplay>
      <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
    </video>


    Outside the question, those functions written in php:

    <?php 
    /* HH:MM:SS to (FLOAT)seconds ------------------*/
    function timerToSec($timer){
      $vtimer = explode(":",$timer);
      $vhours = (int)$vtimer[0];
      $vminutes = (int)$vtimer[1];
      $vseconds = (float)$vtimer[2];
      return $vhours * 3600 + $vminutes * 60 + $vseconds;
    }
    /* Seconds to (STRING)HH:MM:SS -----------------*/
    function secToTimer($sec){
      return explode(" ", date("H:i:s", $sec))[0];  
    }
    
    0 讨论(0)
  • 2020-11-22 10:32
    var time1 = date1.getTime();
    var time2 = date2.getTime();
    var totalMilisec = time2 - time1;
    
    alert(DateFormat('hh:mm:ss',new Date(totalMilisec)))
    
     /* ----------------------------------------------------------
     *  Field        | Full Form          | Short Form
     *  -------------|--------------------|-----------------------
     *  Year         | yyyy (4 digits)    | yy (2 digits)
     *  Month        | MMM (abbr.)        | MM (2 digits)
                     | NNN (name)         |
     *  Day of Month | dd (2 digits)      | 
     *  Day of Week  | EE (name)          | E (abbr)
     *  Hour (1-12)  | hh (2 digits)      | 
     *  Minute       | mm (2 digits)      | 
     *  Second       | ss (2 digits)      | 
     *  ----------------------------------------------------------
     */
    function DateFormat(formatString,date){
        if (typeof date=='undefined'){
        var DateToFormat=new Date();
        }
        else{
            var DateToFormat=date;
        }
        var DAY         = DateToFormat.getDate();
        var DAYidx      = DateToFormat.getDay();
        var MONTH       = DateToFormat.getMonth()+1;
        var MONTHidx    = DateToFormat.getMonth();
        var YEAR        = DateToFormat.getYear();
        var FULL_YEAR   = DateToFormat.getFullYear();
        var HOUR        = DateToFormat.getHours();
        var MINUTES     = DateToFormat.getMinutes();
        var SECONDS     = DateToFormat.getSeconds();
    
        var arrMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
        var arrDay=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
        var strMONTH;
        var strDAY;
        var strHOUR;
        var strMINUTES;
        var strSECONDS;
        var Separator;
    
        if(parseInt(MONTH)< 10 && MONTH.toString().length < 2)
            strMONTH = "0" + MONTH;
        else
            strMONTH=MONTH;
        if(parseInt(DAY)< 10 && DAY.toString().length < 2)
            strDAY = "0" + DAY;
        else
            strDAY=DAY;
        if(parseInt(HOUR)< 10 && HOUR.toString().length < 2)
            strHOUR = "0" + HOUR;
        else
            strHOUR=HOUR;
        if(parseInt(MINUTES)< 10 && MINUTES.toString().length < 2)
            strMINUTES = "0" + MINUTES;
        else
            strMINUTES=MINUTES;
        if(parseInt(SECONDS)< 10 && SECONDS.toString().length < 2)
            strSECONDS = "0" + SECONDS;
        else
            strSECONDS=SECONDS;
    
        switch (formatString){
            case "hh:mm:ss":
                return strHOUR + ':' + strMINUTES + ':' + strSECONDS;
            break;
            //More cases to meet your requirements.
        }
    }
    
    0 讨论(0)
提交回复
热议问题