例如:如何計算日期紅寶石
td = created_at
ta = updated_at
# is there a clean and nice way to print number of days and hours, minutes??
diff = ta - td
例如:如何計算日期紅寶石
td = created_at
ta = updated_at
# is there a clean and nice way to print number of days and hours, minutes??
diff = ta - td
退房時間類:Ruby 1.9,Ruby 1.8.7
時間是日期和時間 的抽象。時間在內部存儲爲 秒數和微秒數 自1970年1月1日00:00 UTC以來的時間。
退房distance_of_time_in_words,它不會總是給你確切的日子和小時,但其結果往往是更方便用戶。
如果您使用的是純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}
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]
只是普通的紅寶石,或者您使用的軌道? (基於created_at/updated_at)。如果Rails看distance_of_time_in_words(http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words) – Doon 2011-05-09 18:32:51
是的,我正在使用rails? – user659068 2011-05-09 18:36:57