[Ruby] Which class should be used to get date and time in Rails app (Time, DateTime, TimeWithZone)

1 minute read

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.

  • System
  • Environment variable ENV['TZ']
  • application.rb

To check which time zone is set in application.rb, use Time.zone.name.

# 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. For example, 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
[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

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.

  1. Time.now (use the time zone of the environment variable)
  2. DateTime.now (use the time zone of the environment variable)
  3. Time.current (use the time zone of application.rb)
  4. 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
[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

# time zone of application.rb 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

Reference article

I referred to the following article. The article is very detailed. https://qiita.com/jnchito/items/cae89ee43c30f5d6fa2c