ArgumentError DateTime中的无效日期#更改

时间:2011-09-20 07:42:48

标签: ruby ruby-on-rails-3

做的时候

startTime = DateTime.now
startTime = startTime.change(:min => (startTime.min / 5.to_f).ceil * 5)

我们的生产服务器偶尔会产生以下异常

A ArgumentError occurred in controller#action:

invalid date
/opt/ruby-enterprise-1.8.7-2009.10/lib/ruby/1.8/date.rb:1519:in `civil'
vendor/bundle/ruby/1.8/gems/activesupport-3.0.9/lib/active_support/core_ext/date_time/calculations.rb:37:in `change'

我无法弄清楚导致问题的原因,也不能在我的开发环境中重现它。我做错了什么,或者这里发生了什么?我想要做的是创建一个DateTime实例,该实例从现在开始向上舍入到最接近的5分钟。

1 个答案:

答案 0 :(得分:0)

如果DateTime.now.min> 55,然后你将最小值设置为60。

如果您只需要时间部分:

startTime = DateTime.now
new_minute = startTime.min / 5.to_f).ceil * 5
new_hour = DateTime.now.hour

if new_minute == 60
  new_minute = 0
  new_hour = new_hour + 1
end

new_time = startTime.change(:min => new_minute, :hour => new_hour)

如果您需要更多,我建议您使用activesupport。然后你可以做

new_time = startTime + (new_minute - min).minutes