Saturday, August 8, 2009

Calculate And Format Due Date In Words

In my todo application, I want to show the due date in years, months, weeks and days... I saw many sites have this feature but I couldn't find any available source code by googling. So I decide to implment my own. It is premature and only server simple purposes. If you find it helpful and save you some time, feel free to copy and use it. It's a helper method added into your application helper or any helper in your rails application.


# Helper method to calculate a string presentation of days from due
def due_from(due_date)
  return "long-term" if due_date == nil
  return "overdue" if due_date.past?
  return "today" if due_date.today?  
  today = Date.today
  return "tomorrow" if due_date == today.tomorrow

  diff_year = due_date.year - today.year  
  diff_month = due_date.month - today.month
  diff_day = due_date.day - today.day  
  diff_week = diff_day/7
  diff_month = diff_month -1 if diff_day < diff_year =" diff_year" y_str = " #{diff_year} "> 1? "years" : "year")
  m_str = " #{diff_month} " + (diff_month > 1? "months" : "month")
  w_str = " #{diff_week} " + (diff_week > 1? "weeks" : "week")
  diff_day = days_in(today.month) + diff_day if diff_day < d_str = " #{diff_day} "> 1? "days" : "day")

  if diff_year > 0
    if diff_month > 0
      return y_str + m_str
    else
      return y_str
    end    
  end

  if diff_month > 0
    if diff_week > 0
      return m_str + w_str
    else
      return m_str
    end
  end

  if diff_week > 0
    diff_wd = diff_day%7
    if diff_wd > 0      
      d_str = " #{diff_wd} " + (diff_wd > 1? "days" : "day")
      return w_str + d_str
    else
      return w_str
    end
  end

  return d_str
end

 def days_in(month)
   (Date.new(Time.now.year,12,31).to_date<<(12-month)).day    end 



Below is the actual effect: the due date is displayed as word description

Show due date in meaningful words

No comments :

Post a Comment