使用ruby中的DateTime方法



我正在使用Visual Ruby开发一个应用程序。在这里,我从下面的下拉菜单中获取日期:

check_to_in_1 = @builder.get_object("cellrenderertext7")

然后我使用split方法分割这个日期:

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

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

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'

我不知道该怎么办,有谁能帮我走出困境吗?

从调用堆栈跟踪中可以看出,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)>

我假设您的日期格式为年/月/日,如果它们的格式为年/日/月,您只需将第二个参数中的%m%d交换为strptime

最新更新