我不能爲我的生活得到日期比較在這個腳本中工作。我試過Date.strpTime,Date.parse,to_date和我最近的嘗試,將字符串轉換爲一個整數,然後從中創建一個新的日期,每次嘗試時,我都會收到「無效日期」錯誤。我正在使用Ruby 2.2.3。任何幫助我如何可以正確解析日期將不勝感激。字符串日期轉換錯誤Ruby
require 'date'
def exec_script
fpAcct = {
'001xxxxxxxxxxx1' => '1-1-1980',
'001xxxxxxxxxxx2' => '1-1-1980',
'001xxxxxxxxxxx3' => '1-1-1980',
'001xxxxxxxxxxx4' => '1-1-1980',
'001xxxxxxxxxxx5' => '1-1-1980',
'001xxxxxxxxxxx6' => '1-1-1980'
}
CSV.open("afile4.csv", 'w') do |writer|
fpAcct.each_key do |acct|
newDate = Date.new(1980,1,1);
ACCTTOOPPDATE.each_key do |ct|
components = ACCTTOOPPDATE[ct].slice(21..-1).split('-')
components2 = fpAcct[acct].split('-')
goodDate = Date.new(components[2].to_i, components[1].to_i, components[0].to_i)
goodDate2 = Date.new(components2[2].to_i, components2[1].to_i, components2[0].to_i)
if acct == ACCTTOOPPDATE[ct].slice(0..17) && goodDate2 < goodDate
newDate = goodDate
end
end
fpAcct[acct] = newDate
writer << [acct, fpAcct[acct]]
end
end
end
ACCTTOOPPDATE = {
'001xxxxxxxxxxxa' => '001xxxxxxxxxxxx1 + 8-28-2015',
'001xxxxxxxxxxxb' => '001xxxxxxxxxxxx2 + 1-7-2015',
'001xxxxxxxxxxxc' => '001xxxxxxxxxxxx3 + 1-8-2015',
'001xxxxxxxxxxxd'' => '001xxxxxxxxxxxx4 + 1-8-2015',
'001xxxxxxxxxxxe' => '001xxxxxxxxxxxx5 + 8-4-2014'
}
exec_script
注:如果我註釋掉的代碼Date.new賦值語句部分,取而代之的是...
puts components[2].to_i
puts components[1].to_i
puts components[0].to_i
puts
puts components2[2].to_i
puts components2[1].to_i
puts components2[0].to_i
我得到(用於循環迭代的一個爲例) :
2015
10
7
1980
1
1
所以我知道我在我的字符串操作語句中抓取字符串的右側部分。我只是不確定爲什麼我無法從中創建日期,並且總的來說爲什麼我無法用其他標準方法解析該字符串以便首先獲取日期。
***更新:
(獲得上解決發行日期的幫助後,我注意到一個重大的邏輯缺陷和固定,所以我想我會更新,在這裏也一樣):
CSV.open("afile4.csv", 'w') do |writer|
fpAcct.each_key do |acct|
newDate = Date.strptime(fpAcct[acct], "%m-%d-%Y")
ACCTTOOPPDATE.each_key do |ct|
components = (ACCTTOOPPDATE[ct].match(/\+ (.*)/))[1]
goodDate = Date.strptime(components, "%m-%d-%Y")
if acct == ACCTTOOPPDATE[ct].slice(0..17) && goodDate > newDate
newDate = goodDate
end
end
writer << [acct, newDate]
end
末 結束
只是一個評論,這是地道的在Ruby中使用,而不是駱駝情況下蛇的情況下:'new_date' VS'newDate'。 – Mohamad