2011-05-09 98 views
2

例如:如何計算日期紅寶石

td = created_at 
ta = updated_at 

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

只是普通的紅寶石,或者您使用的軌道? (基於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

+0

是的,我正在使用rails? – user659068 2011-05-09 18:36:57

回答

-1

退房時間類:Ruby 1.9Ruby 1.8.7

時間是日期和時間 的抽象。時間在內部存儲爲 秒數和微秒數 自1970年1月1日00:00 UTC以來的時間。

+2

這是如何幫助? – oma 2011-05-09 18:36:59

+0

我以某種方式誤解「打印天數和小時數,分鐘數的好方法」嗎? – 2011-05-09 18:41:28

+0

顯示了一些示例代碼,而不是僅僅引用文檔 – jgauffin 2011-05-09 18:59:51

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} 
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]