开发者

How to evaluate a date difference in years, months and days (ruby)?

I have to make a simple difference betw开发者_开发问答een two dates:

Date.parse("2009-06-20") - Date.today

This gives me the difference of the dates in days.

Anyone know a way to easily convert that to the following format:

The event occurred X years, Y months and Z days ago

Thank you.


Found the answer here:

More precise distance_of_time_in_words

with this gem:

https://github.com/radar/dotiw


You may be looking for distance_of_times_in_words


There is a RubyGem which returns Time difference in a hash like {:year => 0, :month => 0,...}

The link is : https://rubygems.org/gems/time_diff


This is an example for difference in days, hours, seconds. Add the fields that you need.

def calculate_difference
  minutes = (Date.parse("2009-06-20") - Date.today).to_i / 60
  days = minutes / (24*60)
  minutes -= days * 24*60
  hours = minutes / 60
  minutes -= hours * 60
  "#{days}d#{hours}h#{minutes}m"
end


I find these generic date differences useful in many cases:

time_a = Time.zone.parse('2020-05-30')
time_b = Time.zone.parse('2010-01-18')

time_diff = {
  years: time_a.year - time_b.year,
  months: time_a.month - time_b.month,
  days: time_a.day - time_b.day,
}
=> {:years=>10, :months=>4, :days=>12}


I don't know of any standard, correct way to do this. As odd as it may seem the standard Ruby library has a Date class but no DateSpan functionality. Rails has a solution but it feels somewhat of a pain for me to require this whole mammoth for such a trivial task.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜