Skip to content

Instantly share code, notes, and snippets.

@localhostdotdev
Last active February 24, 2019 22:33
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 localhostdotdev/be52fad4dda2d5ba6bc539aebb4ba347 to your computer and use it in GitHub Desktop.
Save localhostdotdev/be52fad4dda2d5ba6bc539aebb4ba347 to your computer and use it in GitHub Desktop.
Get relative time in the past (with a shorter output option)
class RelativeTime
MINUTE = 60
HOUR = 60 * MINUTE
DAY = 24 * HOUR
WEEK = 7 * DAY
MONTH = 4 * WEEK
YEAR = 12 * MONTH
def self.for(date_to, date_from = Time.zone.now, short: false)
diff = (date_from.to_time - date_to.to_time).round
str = "#{verb_agreement(resolution(diff))} ago"
if short
str = str.gsub('years', 'y').gsub('months', 'mo').gsub('weeks', 'w')
str = str.gsub('days', 'd').gsub('hours', 'h').gsub('minutes', 'm')
str = str.gsub('seconds', 's').gsub('an hour', 'h').gsub('a ', '1')
str = str.gsub('ago', '').gsub(' ', '')
end
str
end
def self.resolution(diff)
if diff >= YEAR * 2
[(diff / YEAR).round, 'years']
elsif diff >= MONTH * 2
[(diff / MONTH).round, 'months']
elsif diff >= WEEK * 2
[(diff / WEEK).round, 'weeks']
elsif diff >= DAY * 2
[(diff / DAY).round, 'days']
elsif diff >= HOUR * 2
[(diff / HOUR).round, 'hours']
elsif diff >= MINUTE * 2
[(diff / MINUTE).round, 'minutes']
else
[diff.round, 'seconds']
end
end
def self.verb_agreement(resolution)
if resolution[0] == 1 && resolution.last == 'hours'
'an hour'
elsif resolution[0] == 1
"a #{resolution.last[0...-1]}"
else
resolution.join(' ')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment