RailsでのtimezoneをUTCにする

October 27, 2014
ruby rails rails4 timezone UTC JST datetime timestamp 時間

Railsで時間情報を扱う場合、JSTだとグローバル対応した時にいろいろ面倒。

なのでデータ情報は全てUTCで扱って、取得するときのみJSTに変換するようにする。

注意点としては以下の通り。

  • modelでdatetime型に情報を渡す場合、ActiveSupport::TimeWithZone型で渡しておく。
  • modelでdatetime型から情報を受け取る場合、JST時間に変換する。
  • 現在時刻を扱う場合、Time.nowは使わずにTime.zone.nowを使う。

設定

日本在住の場合、初期設定時は以下のようになっている。

種類 初期値
Rails UTC
Rails ActiveRecord UTC
Heroku UTC
Heroku Postgres UTC
Amazon RDS UTC
OS JST
Homebrew(PostgreSQL) JST

Rails、Heroku、RDS、OS辺りは特に設定はいらない。

自分のPCにpostgreSQLをインストールした場合はtimezoneをUTCに設定しておく

以下のplaysテーブルを例として考える。

まずmodelを作成する。

$ rails g model play played_at:datetime

現在の時間を渡す場合

class Play < ActiveRecord::Base
  play = Play.new()
  play.played_at = Time.zone.now
  play.save
end

文字列の時間を渡す場合

class Play < ActiveRecord::Base
  d_time = "Mon, 27 Oct 2014 17:44:24 +0900"
  played_at = DateTime.strptime(d_time, '%a, %d %b %Y %T %z').in_time_zone

  play = Play.new()
  hoge.played_at = played_at
  play.save
end

modelから時間を取得する場合

class Play < ActiveRecord::Base
  play1 = Play.find(1)
  played_time = play1.played_at.in_time_zone('Tokyo')
end