3

我正在使用 Visual Ruby 开发一个应用程序。我正在从如下下拉列表中获取日期:

check_to_in_1 = @builder.get_object("cellrenderertext7")

split然后我使用以下方法拆分此日期:

date_split = check_to_in_1.text.to_s.split("/")

我这样做是因为我想将日期从转换StringDateTime格式,拆分后我打印如下值:

puts "#{date_split[2]}"  # => 05
puts "#{date_split[1]}"  # => 10
puts "#{date_split[0]}"  # => 2013

现在我将此值传递给DateTime.new方法以将其转换为DateTime

check_to_in_time_converted = DateTime.new(date_split[0], 
                                          date_split[1], date_split[2])

现在在这里我得到了这个错误:

C:/Users/abhiram/visualruby/examples/fedena/bin/SendAbsentees.rb:213:in `new': undefined method `div' for "05":String
 from C:/Users/abhiram/visualruby/examples/fedena/bin/SendAbsentees.rb:213:in `button1_clicked'
 from C:/Ruby193/lib/ruby/gems/1.9.1/gems/gtk2-1.2.1-x86-mingw32/lib/gtk2/base.rb:95:in `call'
 from C:/Ruby193/lib/ruby/gems/1.9.1/gems/gtk2-1.2.1-x86-mingw32/lib/gtk2/base.rb:95:in `block in __connect_signals__'
 from C:/Ruby193/lib/ruby/gems/1.9.1/gems/vrlib-0.0.33/lib/GladeGUI.rb:331:in `call'
 from C:/Ruby193/lib/ruby/gems/1.9.1/gems/vrlib-0.0.33/lib/GladeGUI.rb:331:in `main'
 from C:/Ruby193/lib/ruby/gems/1.9.1/gems/vrlib-0.0.33/lib/GladeGUI.rb:331:in `show_window'
 from C:/Users/abhiram/visualruby/examples/fedena/bin/SendAbsentees.rb:99:in `show'
 from C:/Users/abhiram/visualruby/examples/fedena/bin/Control.rb:36:in `button2_clicked'
 from C:/Ruby193/lib/ruby/gems/1.9.1/gems/gtk2-1.2.1-x86-mingw32/lib/gtk2/base.rb:95:in `call'

我不知道从这里该怎么办,有人可以帮我摆脱困境吗?

4

1 回答 1

3

正如您在调用堆栈跟踪中看到的那样,DateTime.new将方法发送到未定义div的字符串:"05"

[...]/bin/SendAbsentees.rb:213:in `new': undefined method `div' for "05":String

那是因为DateTime.new期望整数作为参数。date_split在将元素传递给之前,您必须将它们转换为整数DateTime.new

DateTime.new(*date_split.map(&:to_i))

更好的是,您可以在不拆分字符串的情况下使用DateTime.strptime而不是DateTime.new,如下所示:

DateTime.strptime(check_to_in_1.text.to_s, '%Y/%m/%d')
# => #<DateTime: 2013-05-10T00:00:00+00:00 ((2456423j,0s,0n),+0s,2299161j)>

我假设您的日期采用 YEAR/MONTH/DAY 格式,如果相反,它们采用 YEAR/DAY/MONTH 格式,您只需%m%d第二个参数中交换strptime.

于 2013-05-18T09:52:39.183 回答