8

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

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

Community
  • 1
  • 1
user1559555
  • 167
  • 1
  • 1
  • 8
  • 2
    http://stackoverflow.com/questions/1322732/convert-seconds-to-hh-mm-ss-with-javascript – Ruben Aug 03 '12 at 09:14
  • 2
    remember if you want to google this, search for javascript, not jQuery because you can still just use javascript between your jQuery code – Ruben Aug 03 '12 at 09:15
  • 1
    "jQuery code" *is* javascript code, `$` is an identifier, `()` invokes it with a `"#string"` string argument. It doesn't change the language in any way. – Esailija Aug 03 '12 at 09:18
  • Ruben, post that answer before I do :) – Peter Rasmussen Aug 03 '12 at 09:21

2 Answers2

42

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));
j08691
  • 204,283
  • 31
  • 260
  • 272
Claudi
  • 5,224
  • 17
  • 30
6

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
Pahomi
  • 455
  • 6
  • 17
Sandy8086
  • 653
  • 1
  • 4
  • 14