【问题标题】:ruby date subtraction红宝石日期减法
【发布时间】:2011-03-29 08:19:34
【问题描述】:

我在 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

谢谢。

【问题讨论】:

  • 您使用什么库或框架为字符串提供to_date 方法?导轨?还有什么?

标签: ruby date datediff


【解决方案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

参考:In Rails, display time between two dates in English

【讨论】:

  • 请不要进行防御性编程
  • 防守?请详细说明。
  • 我知道这意味着什么......就像我从 time 开始检查 to_time 方法一样。正确的塔斯???
【解决方案2】:

我知道这有点脏,但你试过吗:

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"

【讨论】:

  • 我想你错过了 #{result.month-1},这是因为 Date.new(0) 将 1 月作为一个月。
  • 你是对的。月份从 1 开始。我刚刚更新了答案。谢了。
猜你喜欢
  • 1970-01-01
  • 2019-05-16
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
相关资源
最近更新 更多