2011-03-29 168 views
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 

感謝。

+0

你正在使用哪種庫或框架,爲字符串提供'to_date'方法? Rails的?還有別的嗎? – maerics 2011-03-29 08:23:37

回答

1

你可以試試這個鏈接:

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

OR

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

+0

請不要防守編程 – Reactormonk 2011-03-29 08:47:12

+1

防守?請詳細說明。 – 2011-03-29 09:03:30

+0

我知道它是什麼意思......就像我有時間檢查to_time方法。正確的塔斯? – Ashish 2011-03-29 09:09:31

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" 
+0

我想你錯過了#{result.month-1},這是因爲Date.new(0)以1月爲一個月。 – a5his 2011-03-29 10:26:20

+0

你說得對。幾個月開始1.我剛剛更新了答案。韓國社交協會。 – Edu 2011-03-30 08:44:15