我不能为我的生活得到日期比较在这个脚本中工作。我试过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