【问题标题】:How to compare unix timestamp to ActiveSupport::TimeWithZone?如何将 unix 时间戳与 ActiveSupport::TimeWithZone 进行比较?
【发布时间】:2019-10-01 14:24:17
【问题描述】:

我有一个 1550814673 的 unix 时间戳整数,我想将它与:

Record.first.created_at
=> Fri, 22 Feb 2019 05:51:13 UTC +00:00
Record.first.created_at.class
=> ActiveSupport::TimeWithZone

我试过用这个把整数变成日期时间:

Time.at(1550814673).utc.to_datetime
=> Fri, 22 Feb 2019 05:51:13 +0000

但这并不完全相同,无法与== 运算符进行真实比较

【问题讨论】:

    标签: ruby-on-rails datetime activerecord time activesupport


    【解决方案1】:

    您可以从带有Time.zone.at 的时间戳创建一个新的ActiveSupport::TimeWithZone 实例:

    irb(main):015:0> Time.zone.at(0)
    => Thu, 01 Jan 1970 00:00:00 UTC +00:00
    irb(main):019:0> Time.zone.at(0).class
    => ActiveSupport::TimeWithZone
    

    这也适用于其他工厂方法,例如 nowlocalparse

    您还可以使用 #in_time_zone 转换 Time 或 DateTime 实例。

    irb(main):014:0> Time.at(0).in_time_zone
    => Thu, 01 Jan 1970 00:00:00 UTC +00:00
    

    【讨论】:

    • 但是,如果时区相同,ActiveSupport::TimeWithZone 实例实际上等同于 Time 实例。例如Time.zone.at(1550814673) == Time.at(1550814673).
    【解决方案2】:

    你可以尝试一次使用to_i,它应该会给你一些你可以使用的东西

    date = Date.today
    => Tue, 14 May 2019
    date.to_time.to_i
    => 1557784800
    Time.at(1557784800)
    => 2019-05-14 00:00:00 +0200
    

    【讨论】:

      【解决方案3】:

      改用DateTime

      DateTime.strptime("1318996912",'%s')
      
      => Wed, 19 Oct 2011 04:01:52 +0000
      

      应该返回一些容易消化的东西,然后你可以很容易地做到这一点:

      DateTime.parse("#{Record.first.created_at}") == DateTime.strptime("1318996912",'%s')
      
      => true
      

      DateTime.parse 会自动将TimeWithZone 字符串转换为DateTime 对象以便于比较。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-22
        • 1970-01-01
        • 2014-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-03
        相关资源
        最近更新 更多