Skip to content

Date.today, Time.now can cause incorrect behaviour

We allow the user to set their timezone using the GitLab config files. This sets the Rails timezone settings the the value provided:

[gitlab.yml]
gitlab:
  time_zone: 'Auckland'

[rails console]
pry(main)> Time.zone
=> #<ActiveSupport::TimeZone:0x00007fd56413f650 @name="Auckland", @tzinfo=#<TZInfo::DataTimezone: Pacific/Auckland>, @utc_offset=nil>
pry(main)> Time.zone.utc_offset
=> 43200

# However this does not change the servers Ruby timezone
 pry(main)> Time.now
=> 2020-05-05 01:29:12 +0000
pry(main)> Time.now.gmt_offset # Still set to UTC
=> 0

Because the server and Rails timezones can be different, theres a chance that they might be in different days.

GitLab Rails time System time Issue
NZ UTC GitLab time is in front of server
UTC NZ Server time is in front of GitLab

This can cause issues, and in fact some of our specs fail during certain times of the day:

To reproduce:

  1. Set local PC time to Wellington timezone, 7am. In this case NZ is a day in advance of UTC.
  2. Run a spec such as rspec ./spec/models/concerns/milestoneish_spec.rb:278. Spec should fail.
  3. Set timezone to later in the day, say 7pm NZ time. UTC and NZ time match.
  4. Run spec again. It should now pass.

This particular spec fails because we use Date.today, a Ruby method, which uses the Ruby set timezone on the host.

What we can do to fix potential issues:

  • Replace uses of Time.now with Time.current. This uses Rails timezone (which matches the one specified in gitlab.yml)
  • Replace uses of Date.today with Date.current. This uses Rails timezone (which matches the one specified in gitlab.yml)
  • Write cops to ensure use of the preferred methods.

References:

Edited by Sean Arnold