LoginSignup
55
53

More than 5 years have passed since last update.

任意のタイムゾーンで出力する方法

Last updated at Posted at 2012-09-26

一般的な方法

Timeにはlocaltimeというローカルタイムで出力するためのメソッドがあるが、これはシステムのローカルタイムに依存してしまう。
なので任意のタイムゾーンを出力するにはENV['TZ']の環境変数を一時的に書き換えてlocaltimeを取れば良い

class Time 
  def timezone(timezone = 'UTC')
    old = ENV['TZ']
    utc = self.dup.utc
    ENV['TZ'] = timezone
    output = utc.localtime
    ENV['TZ'] = old
    output
  end
end

@time = Time.now
puts @time.timezone('Asia/Tokyo')      # => 2012-09-26 12:19:18 +0900
puts @time.timezone('America/Chicago') # => 2012-09-25 22:19:18 -0500 

ActiveSupport::TimeWithZone#in_time_zoneを使った方法

Time.zone.now.in_time_zone('America/Chicago') # => 2012-09-25 22:19:18 -0500
55
53
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
55
53