简体   繁体   English

比较Rails中的日期时间变量

[英]Comparing datetime variables in Rails

Rails 3 Ruby 1.92 - i have a helper method comparing a datetime attribute on an object to the current date & time. Rails 3 Ruby 1.92-我有一个辅助方法,将对象上的datetime属性与当前日期和时间进行比较。

module StoreHelper
  def initial_time(product)
    if product.time_type == "Min"
      initial_time = (product.time * 60) 
    elsif product.time_type == "Hrs"
      initial_time = (product.time * 3600)
    else
      initial_time = 0
    end
  end

  def time_based_price(product)
    start_time = product.start_time
    current_time = Time.now
    expire_time = start_time + initial_time(product)

    if (current_time <= expire_time) && (unit_sales(product)>= product.volume)
      time_based_price = (product.price - product.boost_savings)
    else
      time_based_price = product.price
    end
  end
end

when i call it from my view i get error "undefined method `to_datetime' for 0:Fixnum". 当我从视图中调用它时,出现错误“ 0:Fixnum的未定义方法'to_datetime'”。 if i change the comparison line (current_time <= expire_time)to (expire_time >= current_time) i get error"comparison of Fixnum with Time failed" 如果我将比较行(current_time <= expire_time)更改为(expire_time> = current_time),则会收到错误消息“ Fixnum与时间比较失败”

I've tried using .now, .current, .zone.now for both Time and DateTime with no luck. 我已经尝试为时间和日期时间同时使用.now,.current,.zone.now,但没有运气。 When i call the Time.zone.now and expire_time values from my view they have the same format: 当我从我的视图调用Time.zone.now和expire_time值时,它们具有相同的格式:

   2013-11-17 20:48:07 UTC - Time.zone.now
   2013-11-17 16:15:00 UTC  - expire_time

Are you calling this method for each product item in a list? 您是否为列表中的每个产品调用此方法? In that case, looks like for one of the product, no values have been set for start_time, and time_type. 在这种情况下,对于其中一种产品,似乎没有为start_time和time_type设置任何值。 You would get this error when expire_time is 0. But since you have tried the value of expire_time, I believe it must be happening for more product instances and it fails for one of those. 当expire_time为0时,您会收到此错误。但是,由于您尝试了expire_time的值,因此我相信更多的产品实例必定会发生此错误,而其中一个实例却会失败。

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

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