Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn seconds into H:M:S format using jQuery [duplicate]

Possible Duplicate:
convert seconds to HH-MM-SS with javascript?

How can I turn say 125 seconds into 00:02:05 using jQuery?

like image 395
user1559555 Avatar asked Aug 03 '12 09:08

user1559555


People also ask

How do you convert seconds to HH MM SS?

To convert seconds to HH:MM:SS :Multiply the seconds by 1000 to get milliseconds. Pass the milliseconds to the Date() constructor. Use the toISOString() method on the Date object. Get the hh:mm:ss portion of the string.

How do you write seconds in Javascript?

The code below works fine. var mind = time % (60 * 60); var minutes = Math. floor(mind / 60); var secd = mind % 60; var seconds = Math. ceil(secd);

What is the format of jQuery?

jQuery uses CSS syntax to select elements.


2 Answers

Come on! You don't need jQuery to achieve that :-) Here it is a possible snippet:

function secondsTimeSpanToHMS(s) {
  var h = Math.floor(s / 3600); //Get whole hours
  s -= h * 3600;
  var m = Math.floor(s / 60); //Get remaining minutes
  s -= m * 60;
  return h + ":" + (m < 10 ? '0' + m : m) + ":" + (s < 10 ? '0' + s : s); //zero padding on minutes and seconds
}

console.log(secondsTimeSpanToHMS(125));
like image 65
Claudix Avatar answered Sep 22 '22 23:09

Claudix


try this code:

function getTime(seconds) {

    //a day contains 60 * 60 * 24 = 86400 seconds
    //an hour contains 60 * 60 = 3600 seconds
    //a minut contains 60 seconds
    //the amount of seconds we have left
    var leftover = seconds;

    //how many full days fits in the amount of leftover seconds
    var days = Math.floor(leftover / 86400);

    //how many seconds are left
    leftover = leftover - (days * 86400);

    //how many full hours fits in the amount of leftover seconds
    var hours = Math.floor(leftover / 3600);

    //how many seconds are left
    leftover = leftover - (hours * 3600);

    //how many minutes fits in the amount of leftover seconds
    var minutes = Math.floor(leftover / 60);

    //how many seconds are left
    leftover = leftover - (minutes * 60);
    document.write(days + ':' + hours + ':' + minutes + ':' + leftover);
}

Test:

getTime(2490453);​ //-> 28:19:47.55:2853
like image 42
Sandy8086 Avatar answered Sep 22 '22 23:09

Sandy8086