Posted By

misteroneill on 09/28/09


Tagged

time hours minutes seconds duration


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

Nanobyte
lindseywb
LuckyShot


Time in Seconds to h:mm:ss


 / Published in: JavaScript
 

URL: http://www.misteroneill.com

I wrote this for displaying audio/video clip durations. This function takes a single argument (a number of seconds) and returns a formatted string in the format "hh:mm:ss". Hours will not show if the total is less than an hour, minutes will always show. Minutes will show leading zero only if the total is greater than an hour. If less than a minute, will show "0" for minutes. Examples: 1:15:05 (4505 seconds), 36:01 (2161 seconds), 0:45 (45 seconds)

  1. function secondsToHms(d) {
  2. d = Number(d);
  3. var h = Math.floor(d / 3600);
  4. var m = Math.floor(d % 3600 / 60);
  5. var s = Math.floor(d % 3600 % 60);
  6. return ((h > 0 ? h + ":" : "") + (m > 0 ? (h > 0 && m < 10 ? "0" : "") + m + ":" : "0:") + (s < 10 ? "0" : "") + s);
  7. }

Report this snippet  

You need to login to post a comment.