Never been to DZone Snippets before?

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

About this user

http://ozmm.org

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Relative date

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 Relative date PHP snippet.

   1  def rel_date(date)
   2    date = Date.parse(date, true) unless /Date.*/ =~ date.class.to_s
   3    days = (date - Date.today).to_i
   4    
   5    return 'today'     if days >= 0 and days < 1
   6    return 'tomorrow'  if days >= 1 and days < 2
   7    return 'yesterday' if days >= -1 and days < 0
   8    
   9    return "in #{days} days"      if days.abs < 60 and days > 0
  10    return "#{days.abs} days ago" if days.abs < 60 and days < 0
  11    
  12    return date.strftime('%A, %B %e') if days.abs < 182
  13    return date.strftime('%A, %B %e, %Y')
  14  end
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS