Skip to content

Instantly share code, notes, and snippets.

@webinista
Created April 1, 2014 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webinista/9925182 to your computer and use it in GitHub Desktop.
Save webinista/9925182 to your computer and use it in GitHub Desktop.
Formatting time from timestamps. Takes seconds and returns a time string.
function formattime(timeinseconds){
var zeroes = '0', hours, minutes, seconds, time;
/*
Create a new date object and pass our time in seconds as the seconds parameter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
*/
time = new Date(0, 0, 0, 0, 0, timeinseconds, 0);
hours = time.getHours();
minutes = time.getMinutes();
seconds = time.getSeconds()
/*
Padding in case we have single 0 values. Zeroes is a numeric string, not a number.
It will concatenate rather than add.
Slice method documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice
*/
hours = (zeroes + hours).slice(-2);
minutes = (zeroes + minutes).slice(-2);
seconds = (zeroes + seconds).slice(-2);
/* Create a time string. */
time = hours + ':' + minutes + ':' + seconds;
/* Return the duration. */
return time;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment