1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

#Rails ( #Ruby + ActiveSupport ) + Time.use_zone + travel_to で現地時刻=日本時刻=JSTを固定して UTC 変換結果を見て遊ぶ例

Last updated at Posted at 2019-11-28
  • タイムゾーンの9時間の扱いを一生かかっても覚えられる気がしない
  • 足し算と引き算を間違える確率が65%
  • Rubyで遊んでいたらだんだん分かってきた気がするけれど
  • タイムゾーンに慣れ親しむだけで1週間かかって、3日で忘れる気がした
require 'active_support/core_ext'

# 日本時間の年始の時間
jst_beggining_of_year = Time.use_zone('Tokyo') { Time.local(2020, 01, 01, 00, 00, 00) }

# travel するために必要
require 'active_support/testing/time_helpers'
include ActiveSupport::Testing::TimeHelpers

# 日本時間の年始に時間を固定する
travel_to jst_beggining_of_year

# 今日の日付は 2020-01-01
Date.current
# => Wed, 01 Jan 2020

# 現在時刻は 2020-01-01 00:00:00 で JST のタイムゾーンも持っている
Time.now
# => 2020-01-01 00:00:00 +0900

# こちらも同じく
Time.current
# => 2020-01-01 00:00:00 +0900

# Time.nowはRubyのclassだがちゃんとtravelできている
Time.now.class
# => Time

# Time.currentはRails=ActiveSupportのclassみたいだがtravelできている
# Time.zone= を指定していない場合は Ruby の Time.now と同じように働く気がしたが合ってるかな
Time.current.class
# => ActiveSupport::TimeWithZone

# Time.zone.now メソッドでは、Time.zoneの指定をしていないので何も得られない
# Time.currentとは扱いが違うみたいだ
Time.zone.now
# NoMethodError: undefined method `now' for nil:NilClass

# Time.zone 指定を日本時間にする
Time.zone = 'Tokyo'
# => "Tokyo"

# 現在時刻は 2020-01-01 00:00:00 で JST のタイムゾーンや曜日も持っている
Time.zone.now
# => Wed, 01 Jan 2020 00:00:00 JST +09:00

# Time.zone.now は ActiveSupport の class を持っている
Time.zone.now.class
# => ActiveSupport::TimeWithZone

# 今日の日付は 2020-01-01だ
# こちらも Ruby ではなく Rails = ActiveSupport のもの
Date.current
# => Wed, 01 Jan 2020

# Time.zone 指定を日本時間にする
Time.zone = 'UTC'
# => "UTC"

# UTCでいうと今日の日付はまだ、前年の年末だ
Date.current
# => Tue, 31 Dec 2019

# 日本時間の年始の0時は、UTCでいうと9時間遅い、年末の15時だ 
Time.zone.now
# => Tue, 31 Dec 2019 15:00:00 UTC +00:00


Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?