Over a million developers have joined DZone.

Relative Date

DZone's Guide to

Relative Date

Free Resource
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.

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')

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}