2011-11-21 48 views
0

我有一個開始月份(3),開始年份(2004年),並且我有一個結束年份(2008年)。我想計算開始和結束日期之間的單詞時間。這就是我想和它不工作..在Rails中使用distance_of_time_in_words

# first want to piece the start dates together to make an actual date 
# I don't have a day, so I'm using 01, couldn't work around not using a day 
st = (start_year + "/" + start_month + "/01").to_date 
ed = (end_year + "/01/01").to_date 

# the above gives me the date March 1st, 2004 
# now I go about using the method 
distance_of_time_in_words(st, ed) 

..this拋出一個錯誤,「字符串就不是我強迫Fixnum對象」。任何人看到這個錯誤?

回答

1

你不能在Ruby中連接字符串和數字。您應該數字轉換成字符串mliebelt建議或使用string interpolation這樣的:

st = "#{start_year}/#{start_month}/01".to_date 

但對於你的具體情況,我認爲沒有必要對字符串的。你可以那樣做:

st = Date.new(start_year, start_month, 1) 
ed = Date.new(end_year, 1, 1) 
distance_of_time_in_words(st, ed) 

,甚至這樣的:

st = Date.new(start_year, start_month) 
ed = Date.new(end_year) 
distance_of_time_in_words(st, ed) 

docsDate類以獲取更多信息。

+0

謝謝,我試過第二個選項,簡短。 – absolutskyy

0

鑑於您在其中調用該方法的上下文是一個知道從ActionView::Helpers::DateHelper的方法,您應在以下改變:

# first want to piece the start dates together to make an actual date 
# I don't have a day, so I'm using 01, couldn't work around not using a day 
st = (start_year.to_s + "/" + start_month.to_s + "/01").to_date 
ed = (end_year.to_s + "/01/01").to_date 

# the above gives me the date March 1st, 2004 
# now I go about using the method 
distance_of_time_in_words(st, ed) 
=> "almost 3 years" 

所以我加入呼籲to_s的數量,以保證操作+正在工作。構建日期可能有更有效的方法,但是你已經足夠了。

+0

感謝您的幫助milebelt :) – absolutskyy