Convert seconds to HH-MM-SS with JavaScript?

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

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

30条回答
  •  生来不讨喜
    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}
    
    

    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}


    Outside the question, those functions written in php:

提交回复
热议问题