Convert seconds to HH-MM-SS with JavaScript ?

Convert seconds to HH-MM-SS with JavaScript ?

Asked on December 11, 2018 in Javascript.
Add Comment


  • 3 Answer(s)

    Here is the easiest solution,

    Write this code using datejs

    (new Date).clearTime()
              .addSeconds(15457)
              .toString('H:mm:ss');
    

    Recently, the “Moment.js is used widely instead  of date.js

    Answered on December 11, 2018.
    Add Comment

    This code runs successfully,

    We can do this with the help of  javascript Date method. We don’t need any external JavaScript library.

    var date = new Date(null);
    date.setSeconds(SECONDS); // specify value for SECONDS here
    var result = date.toISOString().substr(11, 8);
    
    Answered on December 11, 2018.
    Add Comment

    The solution is,

    You do this for you in a way that’s more convenient than just doing the math yourself.  Because there might be not built-in feature of the standard .Date object

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

    The example is here,

    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);
    
    Answered on December 11, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.