🖥

#Rails ( or #Ruby + ActiveSupport ) + travel で 現地時刻 = JST で特定日付に時間を固定

2019/11/29に公開
# REQUIRE : on Ruby

require 'active_support/testing/time_helpers'
# => true

require 'active_support/core_ext'
# => true

include ActiveSupport::Testing::TimeHelpers
# => Object


# Travel to JST beggining of Year

travel_to Time.use_zone('Tokyo') { Time.parse('2020-01-01 00:00') }
# => nil


# JST

Time.use_zone('Tokyo') { Time.now }
# => 2020-01-01 00:00:00 +0900

Time.use_zone('Tokyo') { Time.current }
# => Wed, 01 Jan 2020 00:00:00 JST +09:00

Time.use_zone('Tokyo') { Time.zone.now }
# => Wed, 01 Jan 2020 00:00:00 JST +09:00

Time.use_zone('Tokyo') { Date.current }
# => Wed, 01 Jan 2020


# UTC


Time.use_zone('UTC') { Time.now }
# => 2020-01-01 00:00:00 +0900

Time.use_zone('UTC') { Time.current }
# => Tue, 31 Dec 2019 15:00:00 UTC +00:00

Time.use_zone('UTC') { Time.zone.now }
# => Tue, 31 Dec 2019 15:00:00 UTC +00:00

Time.use_zone('UTC') { Date.current }
# => Tue, 31 Dec 2019


# Unix Timestamp
# are All same at any Timezone

Time.use_zone('Tokyo') { Time.now.to_i }
# => 1577804400

Time.use_zone('Tokyo') { Time.zone.now.to_i }
# => 1577804400

Time.use_zone('UTC') { Time.now.to_i }
# => 1577804400

Time.use_zone('UTC') { Time.zone.now.to_i }
# => 1577804400

Time.now.to_i
# => 1577804400

Time.current.to_i
# => 1577804400


# Date.today
# Not considered Timezone with Time.zone setting
# its Ruby method refers TZ env

Time.use_zone('Tokyo') { Date.today }
# => Wed, 01 Jan 2020
Time.use_zone('UTC') { Date.today }
# => Wed, 01 Jan 2020

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/2776

チャットメンバー募集

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

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-11-29

Discussion