LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】TimeWithZoneクラスとは

Posted at

TimeWithZoneクラス

  • Rails独自のクラスで、Timeクラスと完全な互換性がある。ただし、実装としてはTimeクラスを継承して作られているわけではない。(親クラスはObject)
  • Timeクラスよりもタイムゾーンを柔軟に扱うことができる。
  • TimeWithZoneクラスのインスタンスはnewではなく、以下のような方法で取得するのが望ましい。
Time.zone = 'Eastern Time (US & Canada)'        # => 'Eastern Time (US & Canada)'
Time.zone.local(2007, 2, 10, 15, 30, 45)        # => Sat, 10 Feb 2007 15:30:45.000000000 EST -05:00
Time.zone.parse('2007-02-10 15:30:45')          # => Sat, 10 Feb 2007 15:30:45.000000000 EST -05:00
Time.zone.at(1171139445)                        # => Sat, 10 Feb 2007 15:30:45.000000000 EST -05:00
Time.zone.now                                   # => Sun, 18 May 2008 13:07:55.754107581 EDT -04:00
Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone  # => Sat, 10 Feb 2007 15:30:45.000000000 EST -05:00

Time.nowとTime.currentの違い

  • Time.nowはTimeクラスで、Time.currentはTimeWithZoneクラス
Time.now
#=> 2021-12-04 18:00:14.633429 +0900
Time.now.class
#=> Time
Time.current
#=> Sat, 04 Dec 2021 18:00:26.016045000 JST +09:00
Time.current.class
#=> ActiveSupport::TimeWithZone

クラスを変換する

#TimeWithZoneクラスのオブジェクトに変換
t = Time.now
#=> 2021-12-04 18:12:54.8637452 +0900
t.in_time_zone
#=> Sat, 04 Dec 2021 18:12:54.863745200 JST +09:00

#Timeクラスのオブジェクトに変換
t = Time.current
#=> Sat, 04 Dec 2021 18:18:05.964407500 JST +09:00
t.to_time
#=> 2021-12-04 18:18:05.9644075 +0900

注意

DateTimeクラスは非推奨なクラスとなったためTimeクラスを使うほうがよい。

参考

0
0
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
0
0