【问题标题】:Time conversion Ruby on Rails 4 not working时间转换 Ruby on Rails 4 不工作
【发布时间】:2016-09-19 15:06:39
【问题描述】:

我向供应商发送电子邮件的部分逻辑是承诺日期必须小于今天的日期才能发送电子邮件。无论出于何种原因,即使它应该是假的,它也会作为真传递。我在控制台中对其进行了测试,它显示为假,但它发送了电子邮件......所以我猜它是通过的。

def self.send_vendor_openorder_notification(user, vendor)
    po_collection = Array.new
    user.purchase_orders.where({open_order: true, vendor_number: vendor.vendor_number}).where.not(email_last_sent: Time.now.midnight).each do |x|
      if x.promise_date == nil || DateTime.strptime(x.promise_date, '%m/%d/%y') + 7.hours < Time.now.midnight
        if x.email_sent == false
          po_collection << x.id
          x.email_sent = true
          x.email_last_sent = Time.now.midnight
          x.save
        end
      end
    end
    if po_collection.empty? == false
      VendorSender.open_order_sender(user, vendor, po_collection).deliver_later
    end
  end

在这里,如果 promise_date 为 nil 或小于今天的午夜,它应该会过去。但是,“2016 年 9 月 19 日”的承诺日期将在 2016 年 9 月 19 日通过。在 heroku 控制台中(这是通过 Heroku 部署的),这是错误的......我在这里错过了什么?

irb(main):038:0> DateTime.strptime("09/19/16", '%m/%d/%y') + 7.hours < Time.now.midnight
=> false
irb(main):039:0> DateTime.strptime("09/19/16", '%m/%d/%y') + 7.hours
=> Mon, 19 Sep 2016 07:00:00 +0000
irb(main):040:0> Time.now.midnight
=> 2016-09-19 00:00:00 -0700
irb(main):041:0> 

【问题讨论】:

  • 它返回 false 因为两个日期完全相同,并且您询问 Time.now.midnight 是否低于 DateTime.strptime。
  • @luissimo 是正确的,日期相同,但时区不同。
  • 我希望它返回 false。问题是它返回 true

标签: ruby-on-rails ruby datetime heroku


【解决方案1】:

我认为问题出在您的 TimeZone 上。

始终使用Time.zone.now 而不是Time.nowClick here 了解更多详情。

您可以像这样更改您的if 条件。

x.promise_date == nil || (Time.zone.parse(x.promise_date.strftime('%Y-%m-%d'))) + 7.hours < Time.zone.now.midnight

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2014-01-12
    • 2014-01-05
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 2013-12-13
    • 1970-01-01
    相关资源
    最近更新 更多