简体   繁体   English

ArgumentError在Ruby版本1.8.6上创建Time类的实例

[英]ArgumentError creating instance of Time class on Ruby version 1.8.6

I'm trying to get the time value using datetime_select from the view, return values obtained are: 我正在尝试使用视图中的datetime_select获取时间值,返回的值是:

"scheduletime"=>{"scheduletime(1i)"=>"2014", "scheduletime(2i)"=>"1", "scheduletime(3i)"=>"9", "scheduletime(4i)"=>"10", "scheduletime(5i)"=>"33"}

In controller I'm trying to create the instance of Time class using the return values of datetime_select. 在控制器中我试图使用datetime_select的返回值创建Time类的实例。 In following manner. 以下列方式。

schedule_time = Time.new(params[:scheduletime]["scheduletime(1i)"], params[:scheduletime]["scheduletime(2i)"], params[:scheduletime]["scheduletime(3i)"], params[:scheduletime]["scheduletime(4i)"], params[:scheduletime]["scheduletime(5i)"],0, "+09:00")

Trying this I'm getting following error. 尝试这个我得到以下错误。

ArgumentError (wrong number of arguments (7 for 0))

The version of ruby I'm using is 1.8.6 . 我使用的ruby版本是1.8.6。 Can any one suggest me where I'm going wrong. 任何人都可以告诉我哪里出错了。

Time.new in Ruby 1.8.6 did not allowed any param. Ruby 1.8.6中的Time.new不允许任何参数。 See the official documentation . 请参阅官方文档

a = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
b = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
a == b            #=> false
"%.6f" % a.to_f   #=> "1049896563.230740"
"%.6f" % b.to_f   #=> "1049896563.231466"

My suggestion is to use Time.utc in order to create a date with given params. 我的建议是使用Time.utc来创建一个给定参数的日期。

You can rewrite the code using Hash#valutes_at 您可以使用Hash#valutes_at重写代码

Time.utc(*params[:scheduletime].values_at(%w( scheduletime(1i) scheduletime(2i) scheduletime(3i) scheduletime(4i) scheduletime(5i) )))

Note that Time.utc also accepts an optional time zone (given I see you are passing one). 请注意, Time.utc也接受一个可选的时区(鉴于我看到你正在传递一个)。


As a side note, you definitely need to upgrade your Ruby version. 作为旁注,您肯定需要升级您的Ruby版本。

The documentation seems to point that you can't pass arguments to the Time.new method. 文档似乎指出您不能将参数传递给Time.new方法。

Try this instead (will use your current TimeZone): 试试这个(将使用您当前的TimeZone):

schedule_time = Time.local(params[:scheduletime]["scheduletime(1i)"], params[:scheduletime]["scheduletime(2i)"], params[:scheduletime]["scheduletime(3i)"], params[:scheduletime]["scheduletime(4i)"], params[:scheduletime]["scheduletime(5i)"],0)

# some variants, using standard TimeZone:
Time.utc(2000,"jan",1,20,15,1)  #=> Sat Jan 01 20:15:01 UTC 2000
Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
Time.local(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000

You might want to set the TimeZone to a different one after that. 您可能希望在此之后将TimeZone设置为另一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM