0

我正在做 Jumpstart Lab 的事件管理器问题,并且已经解决了一天中的时间问题。推荐的方法#strparse 在第一次输入时给了我这个问题,所以我环顾四周并使用了 DT.parse() 和 #strftime,它解析了前几次但在 8 之后就死了……嗯,你会看到的。

我在 Win 7 和 OSX 10.7 上试过这个。都 Ruby 1.9.3

require "csv"
require 'date'

contents = CSV.open "C:\\Users\\...\\Desktop\\event_manager\\event_attendees.csv", headers: true,         header_converters: :symbol


def time_of_day(row, id)
    raw_date = row[:regdate]
    if raw_date[-5] == ' ' #Thought the problem might be related to padding
        #raw_date = raw_date.insert(-5, '0')
        return time_of_day_2(raw_date, id)

    end
    p raw_date + " ID: #{id}"
    new_date = DateTime.parse(raw_date) #Line 48
    new_date = new_date.strftime('%l:%M %p')
    new_date +  "ID: #{id}"
end                            


def time_of_day_2(raw_date, id)
    p raw_date + " ID: #{id}"
    '00:00'
end

contents.each do |row|
    name = row[:first_name].capitalize
id = row[0] 
    time_of_day = time_of_day(row, id) #Line 71
    p time_of_day
end

结果是这样的:

"11/12/08 10:47 ID: 1"
"10:47 AM ID: 1"
C:/Users/.../Desktop/event_manager/lib/event_manager.rb:48:in `parse"11/12/08 13:23 ID: 2" #I don't know why it prints this up here
" 1:23 PM ID: 2"
"11/12/08 13:30 ID: 3"
" 1:30 PM ID: 3"
"11/12/08 14:04 ID: 4"
" 2:04 PM ID: 4"
"11/12/08 14:46 ID: 5"
" 2:46 PM ID: 5"
"11/12/08 15:00 ID: 6"
" 3:00 PM ID: 6"
"11/12/08 16:05 ID: 7"
" 4:05 PM ID: 7"
"11/12/08 17:18 ID: 8"
" 5:18 PM ID: 8"
"11/13/08 1:32 ID: 9"
"00:00"
"11/13/08 16:40 ID: 10"
': invalid date (ArgumentError)
    from C:/Users/.../Desktop/event_manager/lib/event_manager.rb:48:in `time_of_day'
    from C:/Users/.../Desktop/event_manager/lib/event_manager.rb:71:in `block in <main>'
    from C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/csv.rb:1792:in `each'
    from C:/Users/.../Desktop/event_manager/lib/event_manager.rb:59:in `<main>'
[Finished in 2.7s with exit code 1]

先感谢您

4

1 回答 1

0

DateTime.parse解释11/13/08为 YY/MM/DD。没有第 13 个月。

使用Datetime::strptimewhich 实现 POSIXstrptime(3)格式代码以更好地控制日期/时间解析格式:

> DateTime.strptime('11/13/08 16:40','%m/%d/%y %H:%M')
=> #<DateTime: 2008-11-13T16:40:00+00:00 ((2454784j,60000s,0n),+0s,2299161j)>
于 2013-04-03T15:31:09.783 回答