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

后端 未结 5 1696
后悔当初
后悔当初 2021-01-04 03:06

I have to make a simple difference between two dates:

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

This gives me the difference of the dates in

相关标签:
5条回答
  • 2021-01-04 03:47

    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 讨论(0)
  • 2021-01-04 03:54

    Found the answer here:

    More precise distance_of_time_in_words

    with this gem:

    https://github.com/radar/dotiw

    0 讨论(0)
  • 2021-01-04 03:55

    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
    
    0 讨论(0)
  • 2021-01-04 04:05

    You may be looking for distance_of_times_in_words

    0 讨论(0)
  • 2021-01-04 04:09

    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

    0 讨论(0)
提交回复
热议问题