2015-10-15 137 views
1

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

末 结束

+0

只是一个评论,这是地道的在Ruby中使用,而不是骆驼情况下蛇的情况下:'new_date' VS'newDate'。 – Mohamad

回答

0

我建议您更改此:

components = ACCTTOOPPDATE[ct].slice(21..-1).split('-') 

要:

components = ACCTOOPPDATE[ct].match(/\+ (.*)/)[1] 

现在我们已经存储在components字符串"8-28-2015"

你说的对,Date.parseDate.new不喜欢MM-DD-YYYY格式。我们可以使用Date#strptime来获取日期对象。 。Date#strptime让我们告诉解析器什么格式字符串在

Date.strptime("8-28-2015", "%m-%d-%Y") 
=> #<Date: 2015-08-28 ((2457263j,0s,0n),+0s,2299161j)> 
+0

当我更改为“nil:NilClass”时,我收到错误“undefined method'[]'”。如果我在最后删除[1],我会得到“没有将MatchData隐式转换为字符串” - 任何想法为什么它不喜欢语法的最后部分? – KB145

+0

没关系!我知道了(与您的建议)。非常感谢!对不起,我不能投票你的答案。我没有足够的声望投票呢:( – KB145

相关问题