Reputation: 11
How to select datetime column with timezone using ActiveRecord::Base.connection.execute()?
e.g
User.first.joined_at => Tue, 31 Jul 2018 05:00:34 MSK +03:00
but
ActiveRecord::Base.connection.execute("SELECT joined_at FROM users") => {"joined_at"=>"2018-07-31 02:00:34.684659"}
Upvotes: 1
Views: 164
Reputation: 434615
ActiveRecord::Base.connection.execute
doesn't understand the database's types that well so you have to parse the strings yourself.
That timestamp should be in UTC as that's the Rails standard inside the database. You could go through Time.zone
:
Time.zone = 'UTC' # Unless your application is already in UTC
t = Time.zone.parse('2018-07-31 02:00:34.684659').in_time_zone('Moscow')
# Tue, 31 Jul 2018 05:00:34 MSK +03:00
Or you could go through DateTime
(which assumes UTC if the string doesn't have a timezone embedded in it):
DateTime.parse('2018-07-31 02:00:34.684659').in_time_zone('Moscow')
# Tue, 31 Jul 2018 05:00:34 MSK +03:00
Upvotes: 1