2

I have a problem with date subtraction in Ruby

"2011-03-29".to_date - "2011-03-20".to_date #=> (9/1)
("2011-03-29".to_date - "2011-03-20".to_date).to_i #=> 9

Seems it's returning the difference between dates in number of days.

Now my problem is to return number of years, months, days of the date difference

ie ("2011-03-29".to_date - "2011-03-20".to_date)

should return

0 years, 0 month and 9 days

Thanks.

Gagan
  • 4,278
  • 7
  • 46
  • 71
  • What library or framework are you using that provides the `to_date` method for a string? Rails? Something else? – maerics Mar 29 '11 at 08:23

2 Answers2

1

You can try this link:

http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words

OR

  def time_diff_in_natural_language(from_time, to_time)
    from_time = from_time.to_time if from_time.respond_to?(:to_time)
    to_time = to_time.to_time if to_time.respond_to?(:to_time)
    distance_in_seconds = ((to_time - from_time).abs).round
    components = []

    %w(year month week day).each do |interval|
      # For each interval type, if the amount of time remaining is greater than
      # one unit, calculate how many units fit into the remaining time.
      if distance_in_seconds >= 1.send(interval)
        delta = (distance_in_seconds / 1.send(interval)).floor
        distance_in_seconds -= delta.send(interval)
        components << pluralize(delta, interval)
      end
    end

    components.join(", ")
  end

  time_diff_in_natural_language(Time.now, 2.5.years.ago)
  >> 2 years, 6 months, 2 days

Reference: In Rails, display time between two dates in English

Community
  • 1
  • 1
Ashish
  • 5,723
  • 2
  • 24
  • 25
1

I know it is kinda dirty but have you tried:

result = Date.new(0) + ("2011-03-29".to_date - "2011-03-20".to_date)
puts "#{result.year} years, #{result.month - 1} months and #{result.day} days"
Edu
  • 1,949
  • 1
  • 16
  • 18