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 ( or #Ruby + ActiveSupport ) + travel で 現地時刻 = JST で特定日付に時間を固定して、それぞれUTC JST timestamp で現在時刻・日付を得る例

Last updated at Posted at 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

チャットメンバー募集

何か質問、悩み事、相談などあれば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?