Skip to content

Instantly share code, notes, and snippets.

@moimikey
Created August 6, 2014 14:11
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 moimikey/263af9d6ac72a4b83988 to your computer and use it in GitHub Desktop.
Save moimikey/263af9d6ac72a4b83988 to your computer and use it in GitHub Desktop.
# Convert int|float from seconds into formatted
# duration timestamp
#
# deps: underscore or lodash or any other library
# that takes over window._ and provides a
# #.compact() method. dep could ultimately
# be removed...
#
# uses double bitwise not `~~` as `Math.floor`
# uses `+` as type coercion to `int`
Util.toHMS = (seconds, options={}) ->
{padding, withSeconds} = options
h = ~~(+seconds / 3600)
m = ~~((+seconds - (h * 3600)) / 60)
s = ~~(+seconds - (h * 3600) - (m * 60)) if withSeconds
# apply pre-padding
if padding
h = (Array(padding + 1).join('0') + h) if h < 10 and h
m = (Array(padding + 1).join('0') + m) if m < 10
s = (Array(padding + 1).join('0') + s) if s < 10 and withSeconds
_.compact([h, m, s]).join(':')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment