如何计算红宝石的日期

时间:2011-05-09 18:26:53

标签: ruby-on-rails ruby

例如:

td = created_at
ta = updated_at

# is there a clean and nice way to print number of days and hours, minutes??
diff = ta - td 

5 个答案:

答案 0 :(得分:2)

结帐distance_of_time_in_words,它并不总能为您提供准确的日期和时间,但通常会让用户更友好。

答案 1 :(得分:0)

如果您使用的是纯Ruby,则可以使用this代码段

require 'date'

class Date
  def distance_to(end_date)
    years = end_date.year - year
    months = end_date.month - month
    days = end_date.day - day
    if days < 0
      days += 30
      months -= 1
    end
    if months < 0
      months += 12
      years -= 1
    end
    {:years => years, :months => months, :days => days}
  end
end

now = Date.today
somewhen =  Date.parse("2010-10-10")

p somewhen.distance_to(now) # => {:years=>0, :months=>6, :days=>29}

答案 2 :(得分:0)

def timespan_in_DHMS(time1, time2)
  # returns an array with number of days, hours, minutes and seconds. 
  days, remaining = (time1-time2).to_i.abs.divmod(86400) 
  hours, remaining = remaining.divmod(3600)
  minutes, seconds = remaining.divmod(60)
  [days, hours, minutes, seconds]
end

t1 = Time.new(2000,1,1)
t2 = Time.new(2100,1,1)
p timespan_in_DHMS(Time.now, t1) #=>[4146, 23, 4, 29]
p timespan_in_DHMS(Time.now, t2) #=>[32378, 0, 55, 30]

答案 3 :(得分:-1)

查看时间类:Ruby 1.9Ruby 1.8.7

  

时间是日期和时间的抽象   倍。时间在内部存储为   秒数和微秒数   从1970年1月1日00:00开始   UTC。

答案 4 :(得分:-1)

请参阅Ruby-doc。{/ p>中的Time#strftime