Skip to content

Date.today causes timezone issues in Rails. #2093

@schwern

Description

@schwern

Describe the bug

Any Faker method which uses Date.today in Ruby On Rails is potentially off by a day. There are similar potential issues for Time.now and DateTime.now.

To Reproduce

In Rails console, set a time zone which is in a different day. For example, right now it is July 27th in my local time zone, but July 28th in UTC. Date.today will return July 27th (local date), but Date.current will return July 28th (application's date).

[47] pry(main)> Time.zone = "UTC"
=> "UTC"
[53] pry(main)> Date.today
=> Mon, 27 Jul 2020
[54] pry(main)> Date.current
=> Tue, 28 Jul 2020

Now functions like Faker::Date.forward will be off by one with respect to the application's time zone.

[60] pry(main)> Faker::Date.forward(days: 1)
=> Tue, 28 Jul 2020

Expected behavior

I expect Faker::Date.forward(days: 1) to return Wed, 29 Jul 2020 which is 1 day forward in the application's time zone.

Additional context

This has been causing mysterious edge-case problems when using Faker data to test Rails validations. For example, Faker::Date.birthday(min_age: 15, max_age: 18) will occassionally fall outside the validation range of on_or_before: -> { 15.years.ago } causing a false test failure.

See https://thoughtbot.com/blog/its-about-time-zones for more detail about which Time and Date methods are safe under Rails.

Perhaps a config option could be added to have Faker use Rails-safe methods such as Date.current and Time.current. Or it could auto-detect a Rails environment.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions