🖥

#Rails ( or #Ruby + ActiveSupport ) の Time.zone.now と Time.current の違い

2019/11/29に公開
require 'active_support/core_ext'


# No Time.zone setting

Time.use_zone(nil) { Time.current }
# => 2019-11-29 07:38:04 +0900

Time.use_zone(nil) { Time.current.class }
# => Time



# with Time.zone setting
# Time.current class changed Time to ActiveSupport::TimeWithZone

Time.use_zone('UTC') { Time.current }
# => Thu, 28 Nov 2019 22:38:20 UTC +00:00

Time.use_zone('UTC') { Time.current.class }
# => ActiveSupport::TimeWithZone

Time.use_zone('UTC') { Time.zone.now }
# => Thu, 28 Nov 2019 22:38:26 UTC +00:00

Time.use_zone('UTC') { Time.zone.now.class }
# => ActiveSupport::TimeWithZone



require 'active_support/testing/time_helpers'
include ActiveSupport::Testing::TimeHelpers

# Freeze time
Time.use_zone('UTC') { travel_to Time.parse('2020-01-01 00:00') }

Time.use_zone('UTC') { Time.current == Time.zone.now }
# => true


# NOTE
# Time.parse class not changed to ActiveSupport::TimeWithZone

Time.parse('2020-01-01 00:00')
# => 2020-01-01 00:00:00 +0900

Time.parse('2020-01-01 00:00').class
# => Time

Time.use_zone('UTC') { Time.zone.parse('2020-01-01 00:00') }
# => Wed, 01 Jan 2020 00:00:00 UTC +00:00

Time.use_zone('UTC') { Time.zone.parse('2020-01-01 00:00').class }
# => ActiveSupport::TimeWithZone


Original by Github issue

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

チャットメンバー募集

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

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

Twitter

https://twitter.com/YumaInaura

公開日時

2019-11-29

Discussion