Search code examples
ruby-on-railsdatetimeactiverecordtimeactivesupport

How to compare unix timestamp to ActiveSupport::TimeWithZone?


I have a unix timestamp integer of 1550814673 and I want to compare it to:

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

I've tried turning the integer into datetime with this:

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

But that is not quite the same and will not compare truthfully with a == operator


Solution

  • You can create a new ActiveSupport::TimeWithZone instance from a timestamp with Time.zone.at:

    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
    

    This also goes for the other factory methods like now, local and parse.

    You can also convert a Time or DateTime instance with #in_time_zone.

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