时区Rails Postgres

时间:2018-08-11 15:40:45

标签: sql ruby-on-rails postgresql select timezone

如何使用ActiveRecord :: Base.connection.execute()选择带有时区的datetime列?

例如

User.first.joined_at => Tue, 31 Jul 2018 05:00:34 MSK +03:00

但是

ActiveRecord::Base.connection.execute("SELECT joined_at FROM users") => {"joined_at"=>"2018-07-31 02:00:34.684659"}

1 个答案:

答案 0 :(得分:1)

ActiveRecord::Base.connection.execute不太了解数据库的类型,因此您必须自己解析字符串。

该时间戳记应采用UTC,因为这是数据库内的Rails标准。您可以通过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 

或者您可以遍历DateTime(如果字符串中未嵌入时区,则假定为UTC):

DateTime.parse('2018-07-31 02:00:34.684659').in_time_zone('Moscow')
# Tue, 31 Jul 2018 05:00:34 MSK +03:00