我在数据库中定义了一些时间,这就是它的外观:
ruby-1.9.2-p290 :017 > djel.smjena.pocetak1.to_time
=> 2000-01-01 08:00:00 +0100
没关系,它给了我2000-1-1 另外,我在某个日期时间发生了一些事情
ruby-1.9.2-p290 :019 > dog.pocetak
=> Thu, 25 Aug 2011 08:18:00 UTC +00:00
所以我希望,.to_time会放弃我的约会,但事实并非如此 发生
ruby-1.9.2-p290 :020 > dog.pocetak.to_time
=> Thu, 25 Aug 2011 08:18:00 UTC +00:00
所以,现在,比较8:00之前发生的事情是否无用。 那么,我该如何比较呢?有没有办法将dog.pocetak设置为 2000-01-01没有触摸时钟?
谢谢
P.S。另外,我想创建新的时间变量,只是为了从旧的变量小时和分钟中获取,但这种方法不起作用?
ruby-1.9.2-p290 :059 > dog.pocetak.hour
=> 8
但
ruby-1.9.2-p290 :060 > dog.pocetak.minute
NoMethodError: undefined method `minute' for 2011-08-25 08:18:00 UTC:Time
from /home/dorijan/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.10/lib/active_support/time_with_zone.rb:322:in `method_missing'
from (irb):60
from /home/dorijan/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands/console.rb:44:in `start'
from /home/dorijan/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands/console.rb:8:in `start'
from /home/dorijan/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
ruby-1.9.2-p290 :061 > dog.pocetak.minutes
NoMethodError: undefined method `minutes' for 2011-08-25 08:18:00 UTC:Time
from /home/dorijan/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.10/lib/active_support/time_with_zone.rb:322:in `method_missing'
from (irb):61
from /home/dorijan/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands/console.rb:44:in `start'
from /home/dorijan/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands/console.rb:8:in `start'
from /home/dorijan/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
非常令人沮丧:)
答案 0 :(得分:3)
要从Time对象获取分钟,您需要min
而不是minutes
。你不能让Time实例只是“一天中的时间”(即没有年,月,......),但你可以使用strftime
来获得一个可以正确比较的字符串版本:
tod = Time.now.strftime('%H:%M:%S')
# "17:07:23"
if(t1.strftime('%H:%M:%S') == t2.strftime('%H:%M:%S'))
# Same time of day (to one second resolution)
end
if(t1.hour == t2.hour && t1.min == t2.min && t1.sec == t2.sec)
# Same time of day (to one second resolution)
end
您采取的方法与往常一样取决于您的具体情况以及该附近地区的其他情况。
答案 1 :(得分:3)
如果您愿意,可以使用ActiveSupport
和Time.change
重置年,月和日:
> t = Time.now
=> Sun Aug 21 00:46:29 +0000 2011
> t.change(:month => 1, :day => 1, :year => 2000)
=> Sat Jan 01 00:46:29 +0000 2000
这样,可以比较彼此之间的“时间”,如果它们全部重置为同一日期。不确定这是否是一个很好的解决方案,取决于你真正想要的是什么。
修改强>:
根据mu的建议,您还可以查看time数据类型。