Skip to content

Instantly share code, notes, and snippets.

@davidchambers
Created November 1, 2012 15:26
Show Gist options
  • Save davidchambers/3994320 to your computer and use it in GitHub Desktop.
Save davidchambers/3994320 to your computer and use it in GitHub Desktop.
Relative timestamp formatting for jQuery.localize
{abs, floor, round} = Math
# > @localize = (timestamp) ->
# . $.localize.format (new Date timestamp), new Date "1 Mar 2012 00:30:45"
#
# > localize "30 Jan 2012 23:59:59"
# "2012-01-30"
# > localize "31 Jan 2012 00:00:00"
# "30 days ago"
# > localize "28 Feb 2012 23:59:59"
# "2 days ago"
# > localize "29 Feb 2012 00:00:00"
# "yesterday"
# > localize "29 Feb 2012 00:30:45"
# "yesterday"
# > localize "29 Feb 2012 00:30:46"
# "23 hours ago"
# > localize "29 Feb 2012 22:30:45"
# "2 hours ago"
# > localize "29 Feb 2012 22:30:46"
# "an hour ago"
# > localize "29 Feb 2012 23:30:45"
# "an hour ago"
# > localize "29 Feb 2012 23:30:46"
# "59 minutes ago"
# > localize "29 Feb 2012 23:59:59"
# "30 minutes ago"
# > localize "1 Mar 2012 00:00:00"
# "30 minutes ago"
# > localize "1 Mar 2012 00:30:35"
# "10 seconds ago"
# > localize "1 Mar 2012 00:30:36"
# "just now"
# > localize "1 Mar 2012 00:30:45"
# "just now"
# > localize "1 Mar 2012 00:35:44"
# "just now"
# > localize "1 Mar 2012 00:35:45"
# "5 minutes from now"
# > localize "1 Mar 2012 00:36:44"
# "5 minutes from now"
# > localize "1 Mar 2012 00:36:45"
# "6 minutes from now"
# > localize "2 Mar 2012 00:30:44"
# "23 hours from now"
# > localize "2 Mar 2012 00:30:45"
# "tomorrow"
# > localize "2 Mar 2012 23:59:59"
# "tomorrow"
# > localize "3 Mar 2012 00:00:00"
# "2 days from now"
# > localize "31 Mar 2012 23:59:59"
# "30 days from now"
# > localize "1 Apr 2012 00:00:00"
# "2012-04-01"
$.localize.format = (date, now = new Date) ->
# Seconds between `date` and `now` (-ve for dates in the past).
delta = (date - now) / 1000
# Assume that times up to five minutes in the future result from
# a discrepancy between server time and that of the user's device.
return 'just now' if -10 < delta < 300
past = delta < 0
delta = abs delta
suffix = if past then 'ago' else 'from now'
# Set the date's time to the current time to facilitate comparison.
date.setHours(
now.getHours()
now.getMinutes()
now.getSeconds()
now.getMilliseconds()
)
# Daylight saving time means that `date - now` isn't necessarily
# divisible by 86400000. It's thus necessary to round the result.
days = abs round (date - now) / (24 * 3600 * 1000)
if days > 30 then $.localize date, 'yyyy-mm-dd'
else if days > 1 then "#{days} days #{suffix}"
else if delta >= 24 * 3600 then (if past then 'yesterday' else 'tomorrow')
else
for [unit, secs] in [['an hour', 3600], ['a minute', 60], ['a second', 1]]
break if delta >= secs
num = floor delta / secs
if num is 1 then "#{unit} #{suffix}"
else "#{num} #{unit.split(' ')[1]}s #{suffix}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment