Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-4460

Date.mongoize(String) should not convert string to local time first

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 7.1.0.rc0
    • Affects Version/s: 6.2.0
    • Component/s: Attributes
    • Labels:
    • Environment:
      Rails: 5.1.2
      Ruby: 2.3.4
      mongod: db version v3.4.6

      Hi,

      I have a Rails app configured to use time zone 'Brasilia'. We discovered the following weird behavior:

      # Correct behavior
      Date.mongoize("2017-06-24") #=> 2017-06-24 00:00:00 UTC
      
      # Wrong behavior?
      Date.mongoize("2017-06-23 00:00:00 UTC") #=> 2017-06-23 00:00:00 UTC
      

      As shown above, if we try to save a model field of type Date by specifying a fully-qualified DateTime, then mongoid will perform some conversions and end up with the wrong date (Jun 23 instead of Jun 24, in this case).

      This happens because the application's time zone is not UTC:

      ::Time.configured #=> #<ActiveSupport::TimeZone:0x00000005298c40 @name="Brasilia", @utc_offset=nil, @tzinfo=#<TZInfo::DataTimezone: America/Sao_Paulo>>
      

      It looks like the problem is in these lines of lib/mongoid/extensions/date.rb:

      # lib/mongoid/extensions/date.rb
      
      #  Returns a ActiveSupport::TimeWithZone object, not necessarily an UTC time.
      time = object.__mongoize_time__
      
      # Creates a new Time as if the previous object were in UTC.
      ::Time.utc(time.year, time.month, time.day)
      

      It seems that the second line should convert back to UTC before creating the new object, like so:

      # Suggestion:
      
      #  Returns a ActiveSupport::TimeWithZone object, not necessarily an UTC time.
      time = object.__mongoize_time__
      
      # Converts before creating Time object
      time = time.utc
      ::Time.utc(time.year, time.month, time.day)
      

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            deborasetton Débora Setton
            Votes:
            1 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: