Convert seconds to HH-MM-SS with JavaScript?

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

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

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

    --update 2

    Please use @Frank's a one line solution:

    new Date(SECONDS * 1000).toISOString().substr(11, 8)
    

    It is by far the best solution.

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

    This does the trick:

    function secondstotime(secs)
    {
        var t = new Date(1970,0,1);
        t.setSeconds(secs);
        var s = t.toTimeString().substr(0,8);
        if(secs > 86399)
            s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
        return s;
    }
    

    (Sourced from here)

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

    Have you tried adding seconds to a Date object?

    var dt = new Date();
    dt.addSeconds(1234);
    

    A sample: https://jsfiddle.net/j5g2p0dc/5/

    Updated: Sample link was missing so I created a new one.

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

    After looking at all the answers and not being happy with most of them, this is what I came up with. I know I am very late to the conversation, but here it is anyway.

    function secsToTime(secs){
      var time = new Date(); 
      // create Date object and set to today's date and time
      time.setHours(parseInt(secs/3600) % 24);
      time.setMinutes(parseInt(secs/60) % 60);
      time.setSeconds(parseInt(secs%60));
      time = time.toTimeString().split(" ")[0];
      // time.toString() = "HH:mm:ss GMT-0800 (PST)"
      // time.toString().split(" ") = ["HH:mm:ss", "GMT-0800", "(PST)"]
      // time.toTimeString().split(" ")[0]; = "HH:mm:ss"
      return time;
    }
    

    I create a new Date object, change the time to my parameters, convert the Date Object to a time string, and removed the additional stuff by splitting the string and returning only the part that need.

    I thought I would share this approach, since it removes the need for regex, logic and math acrobatics to get the results in "HH:mm:ss" format, and instead it relies on built in methods.

    You may want to take a look at the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

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

    You can manage to do this without any external JavaScript library with the help of JavaScript Date method like following:

    var date = new Date(null);
    date.setSeconds(SECONDS); // specify value for SECONDS here
    var result = date.toISOString().substr(11, 8);
    

    Or, as per @Frank's comment; a one liner:

    new Date(SECONDS * 1000).toISOString().substr(11, 8);
    
    0 讨论(0)
  • 2020-11-22 10:37

    As Cleiton pointed out in his answer, moment.js can be used for this:

    moment().startOf('day')
            .seconds(15457)
            .format('H:mm:ss');
    
    0 讨论(0)
提交回复
热议问题