2

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

日数で日付間の差を返しているようです。

今私の問題は、日付の違いの年、月、日数を返すことです

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

戻る必要があります

0 years, 0 month and 9 days

ありがとう。

4

2 に答える 2

1

このリンクを試すことができます:

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

また

  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

参考:Railsでは2つの日付の間の時間を英語で表示

于 2011-03-29T08:43:11.583 に答える
1

私はそれがちょっと汚いことを知っていますが、試しましたか:

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"
于 2011-03-29T08:44:10.680 に答える