如何将 unix 时间戳与 ActiveSupport::TimeWithZone 进行比较?

How to compare unix timestamp to ActiveSupport::TimeWithZone?

我有一个 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

但这并不完全相同,不会如实地与 == 运算符进行比较

改用DateTime

DateTime.strptime("1318996912",'%s')

=> Wed, 19 Oct 2011 04:01:52 +0000

应该return一些容易消化的东西,然后你就可以轻松地做到这一点:

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

=> true

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

您可以尝试使用 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

您可以从带有 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