Which class should be used to get the date and time
- Time class
- DateTime class
- TimeWithZone class
In Rails, unless you have a specific reason It is better to unify with TimeWithZone class rather than Time class and DateTime class.
About time zone
There are three places to set the time zone.
- Environment variable
To check which time zone is set in application.rb, use
# application.rb config.time_zone ='Tokyo' Time.zone.name => "Tokyo"
Which time zone is used
The tricky part is that the timezone used depends on the class and the methods associated with that class.
Time.now using the method
now related to the Time class uses the time zone of the environment variable,
Time.current which uses method
current related to Time class uses the time zone of application.rb.
# Environment variables are used, class is Time  pry(main)> Time.now => 2020-07-31 19:39:18 +0900  pry(main)> Time.now.class => Time # application.rb is used and class becomes TimeWithZone  pry(main)> Time.current => Fri, 31 Jul 2020 19:39:35 JST +09:00  pry(main)> Time.current.class => ActiveSupport::TimeWithZone
Use Time.current or Time.zone.now to get the current date and time
There are the following methods to get the current date and time.
- Time.now (use the time zone of the environment variable)
- DateTime.now (use the time zone of the environment variable)
- Time.current (use the time zone of application.rb)
- Time.zone.now (use the time zone of application.rb)
In conclusion, it is better to use TimeWithZone class 3 or 4 (if you want to make it an international application you can handle it in various ways).
# Environment variable timezone is used  pry(main)> Time.now => 2020-07-31 19:43:14 +0900 #Time class  pry(main)> DateTime.now => Fri, 31 Jul 2020 19:43:21 +0900 #DateTime class # time zone of application.rb is used  pry(main)> Time.current => Fri, 31 Jul 2020 19:43:26 JST +09:00 #ActiveSupport::TimeWithZone class  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 is very detailed. https://qiita.com/jnchito/items/cae89ee43c30f5d6fa2c