mardi 1 mai 2018

Rails AR Date Range Query - Daylight Saving - Overlap

I have a Rails 3 application, how would one avoid an overlap happening due to daylight saving?

My problem is that I am having a form that generate reports. Auditing an inconsistency I noticed that a bunch of transactions show up in the week ending in March 11th also show up in the Week starting on March 12th.

The problem boils down to some thing like this...

Time.zone.parse('2018-03-11').to_datetime.end_of_day.utc
 => Mon, 12 Mar 2018 07:59:59 +0000 
Time.zone.parse('2018-03-12').to_datetime.beginning_of_day.utc
 => Mon, 12 Mar 2018 07:00:00 +0000 

The 1 hour overlap above seem to be where my problem lies. When checking date ranges (see actual code below) how can I avoid this overlap.

Actual Code

Here is the actual code that resemble filtering by date.

  scope :filter_date, lambda { |starts, ends, date, transaction_type = :transaction|
    _scope = scoped


    starts = Time.zone.parse(starts).to_datetime        if starts.class == String and starts.present?
    ends   = Time.zone.parse(ends).to_datetime.tomorrow if ends.class   == String and ends.present?

    begin
      case date
      when 'settled'
        transaction_type == "batch" ? date_field = 'deposited_at' : date_field = 'settled_at'
        _scope = _scope.order('transactions.'+date_field+' DESC')
        _scope = _scope.where("transactions."+date_field+" >= ?", starts) if starts.present?
        _scope = _scope.where("transactions."+date_field+" < ?", ends)   if ends.present?
      else # created, nil, other
        _scope = _scope.order('transactions.created_at DESC')
        _scope = _scope.where("transactions.created_at >= ?", starts) if starts.present?
        _scope = _scope.where("transactions.created_at < ?", ends)   if ends.present?
      end
    end
    _scope
  }

Stack

  • Ruby 2.1
  • Rails 3.2
  • PG

Question

How can I overcome this overlap of time where the daylight saving takes effect.

Aucun commentaire:

Enregistrer un commentaire