Reputation: 790
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
Upvotes: 1
Views: 1231
Reputation: 59
Use DateTime
instead!
DateTime.strptime("1318996912",'%s')
=> Wed, 19 Oct 2011 04:01:52 +0000
Should return something easy to digest, and you can then easily do this:
DateTime.parse("#{Record.first.created_at}") == DateTime.strptime("1318996912",'%s')
=> true
DateTime.parse
will automatically convert the TimeWithZone
string to a DateTime
object for easy comparison.
Upvotes: 0
Reputation: 102222
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
Upvotes: 4
Reputation: 364
You can try to use to_i
on a time, and it should give you something that you could use
date = Date.today
=> Tue, 14 May 2019
date.to_time.to_i
=> 1557784800
Time.at(1557784800)
=> 2019-05-14 00:00:00 +0200
Upvotes: 3