Convert seconds to HH-MM-SS with JavaScript?

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

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

30条回答
  •  时光说笑
    2020-11-22 10:17

    I don't think any built-in feature of the standard Date object will do this for you in a way that's more convenient than just doing the math yourself.

    hours = Math.floor(totalSeconds / 3600);
    totalSeconds %= 3600;
    minutes = Math.floor(totalSeconds / 60);
    seconds = totalSeconds % 60;
    

    Example:

    let totalSeconds = 28565;
    let hours = Math.floor(totalSeconds / 3600);
    totalSeconds %= 3600;
    let minutes = Math.floor(totalSeconds / 60);
    let seconds = totalSeconds % 60;
    
    console.log("hours: " + hours);
    console.log("minutes: " + minutes);
    console.log("seconds: " + seconds);
    
    // If you want strings with leading zeroes:
    minutes = String(minutes).padStart(2, "0");
    hours = String(hours).padStart(2, "0");
    seconds = String(seconds).padStart(2, "0");
    console.log(hours + ":" + minutes + ":" + seconds);

提交回复
热议问题