DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Relative Date

07.20.2005
| 11803 views |
  • submit to reddit
        Pass this method a Date object, a DateTime object, or a string of a date (like 7/6/05) and it will return a response that looks like 'yesterday', 'today', 'tomorrow', '12 days ago', 'in 4 days', 'Monday, January 5', or 'Tuesday, December 15, 2004'.

Inspired by adrian's <a href="http://www.bigbold.com/snippets/posts/show/196">Relative date</a> PHP snippet.

def rel_date(date)
  date = Date.parse(date, true) unless /Date.*/ =~ date.class.to_s
  days = (date - Date.today).to_i
  
  return 'today'     if days >= 0 and days < 1
  return 'tomorrow'  if days >= 1 and days < 2
  return 'yesterday' if days >= -1 and days < 0
  
  return "in #{days} days"      if days.abs < 60 and days > 0
  return "#{days.abs} days ago" if days.abs < 60 and days < 0
  
  return date.strftime('%A, %B %e') if days.abs < 182
  return date.strftime('%A, %B %e, %Y')
end