字符串到日期转换错误Ruby

时间:2015-10-15 22:59:22

标签: ruby string date parsing

我不能为我的生活得到日期比较在这个脚本中工作。我已经尝试过Date.strpTime,Date.parse,to_date和我最近的尝试,将字符串转换为整数然后从中创建一个新日期,并且每次尝试时,我都会收到“无效日期”错误。我正在使用Ruby 2.2.3。任何有关如何正确解析日期的帮助将不胜感激。

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

所以我知道我在字符串操作语句中抓取字符串的右边部分。我只是不确定为什么我不能从它创建一个日期,一般来说为什么我不能通过其他标准来解析该字符串以获得一个日期。

*** UPDATE:

(在获得解决日期问题的帮助之后,我注意到一个主要的逻辑缺陷并修复了它,所以我想我也会在这里更新):

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

端 端

1 个答案:

答案 0 :(得分:0)

我建议你改变这个:

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

要:

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

现在我们将"8-28-2015"存储在components

你是对的,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)>
相关问题