--Time class --DateTime class --TimeWithZone class
In Rails, unless you have a specific reason It is better to unify with the TimeWithZone class rather than the Time class and DateTime class.
There are three places to set the time zone.
--System --Environment variable ʻENV ['TZ'] `
Use Time.zone.name
to see which timezone is set in application.rb.
# application.rb
config.time_zone = 'Tokyo'
Time.zone.name
=> "Tokyo"
To complicate matters, the time zone used depends on the class and the methods associated with it.
For example
Time.now
using the method now
related to the Time class uses the timezone of the environment variable
Time.current
using the method current
associated with the Time class uses the timezone of application.rb.
#Environment variables are used and class becomes Time
[1] pry(main)> Time.now
=> 2020-07-31 19:39:18 +0900
[2] pry(main)> Time.now.class
=> Time
#application.rb is used and class becomes TimeWithZone
[3] pry(main)> Time.current
=> Fri, 31 Jul 2020 19:39:35 JST +09:00
[4] pry(main)> Time.current.class
=> ActiveSupport::TimeWithZone
There are the following methods to get the current date and time.
In conclusion, it's better to use the TimeWithZone class 3 or 4 (because if you want to make it an international application, you can handle it in various ways).
#The timezone of the environment variable is used
[1] pry(main)> Time.now
=> 2020-07-31 19:43:14 +0900 #Time class
[2] pry(main)> DateTime.now
=> Fri, 31 Jul 2020 19:43:21 +0900 #DateTime class
# application.rb timezone is used
[3] pry(main)> Time.current
=> Fri, 31 Jul 2020 19:43:26 JST +09:00 #ActiveSupport::TimeWithZone class
[4] pry(main)> Time.zone.now
=> Fri, 31 Jul 2020 19:43:32 JST +09:00 #ActiveSupport::TimeWithZone class
I referred to the following article. The article explains it in great detail. https://qiita.com/jnchito/items/cae89ee43c30f5d6fa2c
Recommended Posts