我正在使用 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)>
我假设你的日期格式是 YEAR/MONTH/DAY,如果它们的格式是 YEAR/DAY/MONTH,你只需要交换 %m
和 %d
在 strptime
的第二个参数中。
关于ruby - 在 ruby 中使用 DateTime 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16622829/