Skip to content

Instantly share code, notes, and snippets.

@JTBrinkmann
Created January 21, 2016 22:39
Show Gist options
  • Save JTBrinkmann/0471639b3f3de96b6065 to your computer and use it in GitHub Desktop.
Save JTBrinkmann/0471639b3f3de96b6065 to your computer and use it in GitHub Desktop.
time and date formatting functions written in LiveScript
aux =
# formatting
timezoneOffset: new Date().getTimezoneOffset!
getTime: (t = Date.now!) !->
return new Date(t - timezoneOffset *60_000min_to_ms).toISOString! .replace(/.+?T|\..+/g, '')
getDateTime: (t = Date.now!) !->
return new Date(t - timezoneOffset *60_000min_to_ms).toISOString! .replace(/T|\..+/g, ' ')
getDate: (t = Date.now!) !->
return new Date(t - timezoneOffset *60_000min_to_ms).toISOString! .replace(/T.+/g, '')
getISOTime: (t = new Date)!->
return t.toISOString! .replace(/T|\..+/g, " ")
parseISOTime: (t) !->
return new Date(t) - timezoneOffset *60_000min_to_ms
# show a timespan (in ms) in a human friendly format (e.g. "2 hours")
humanTime: (diff, shortFormat) !->
if diff < 0
return "-#{humanTime -diff}"
else if not shortFormat and diff < 2_000ms # keep in sync with ago()
return "just now"
b=[60to_min, 60to_h, 24to_days, 360.25to_years]; c=0
diff /= 1000to_s
while diff > 2*b[c] then diff /= b[c++]
if shortFormat
return "#{Math.round diff}#{<[ s m h d y ]>[c]}"
else
return "#{Math.round diff} #{<[ seconds minutes hours days years ]>[c]}"
# show a timespan (in s) in a format like "mm:ss" or "hh:mm:ss" etc
mediaTime: (dur) !->
return "-#{mediaTime -dur}" if dur < 0
# usually the user would rather read 580 hours as "580:00:00" instead of "24:04:00:00"
m=0
if dur >= 60
m = ~~(dur / 60); dur %= 60
if m >= 60
h = ~~(m / 60); m %= 60
return "#{if h then pad(h)+":" else ''}#{pad(m)}:#{pad(~~dur)}"
# create string saying how long ago a given timestamp (in ms since epoche) is
ago: (d) !->
d = Date.now! - d
if d < 2_000ms # keep in sync with humanTime()
return "just now"
else
return "#{humanTime(d)} ago"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment