【问题标题】:Comparing datetime variables in Rails比较 Rails 中的日期时间变量
【发布时间】:2023-03-29 07:55:02
【问题描述】:

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

当我从我的视图中调用它时,我收到错误“未定义的方法 `to_datetime' for 0:Fixnum”。如果我将比较行 (current_time = current_time) 我得到错误“Fixnum 与时间的比较失败”

我尝试使用 .now、.current、.zone.now 来表示 Time 和 DateTime,但没有成功。当我从我的视图中调用 Time.zone.now 和 expire_time 值时,它们具有相同的格式:

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

【问题讨论】:

  • start_time (product.start_time) 是什么类型?您是否尝试将 product.start_time 解析为 Time 类型?
  • 你试过.to_i日期吗?我认为将日期时间乘以一个数字将返回一个数字。这是那些有趣的转换之一。

标签: ruby-on-rails datetime


【解决方案1】:

您是否为列表中的每个产品项目调用此方法?在这种情况下,看起来对于其中一种产品,没有为 start_time 和 time_type 设置任何值。当 expire_time 为 0 时,您会收到此错误。但由于您已经尝试过 expire_time 的值,我相信它一定会发生在更多产品实例上,而其中一个实例会失败。

【讨论】:

  • 非常感谢你的朋友。我更新了调用 并且效果很好。再次感谢。
  • 后续问题是否有更好的方法来比较 Rails 中的日期时间,例如语法相当于 if some_time 晚于 Time.now 做点什么?
  • 太好了!您能否详细描述后续问题?
  • 现在我正在用这样的语法比较时间:if (current_time 符号。基本上我想知道是否有更具体的时间变量的比较方法。我担心的是,在进行正常的比较时,AM/PM 可能存在问题。
猜你喜欢
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 2013-02-04
相关资源
最近更新 更多