Rails AR日期范围查询 - 夏令时 - 重叠

时间:2018-05-01 08:20:23

标签: ruby-on-rails ruby postgresql ruby-on-rails-3 activerecord

我有一个Rails 3应用程序,如何避免由于夏令时发生重叠?

我的问题是我有一个生成报告的表单。审核不一致我注意到在3月11日结束的那一周出现的一堆交易也出现在3月12日的一周内。

问题归结为这样的事情......

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 

上面的1小时重叠似乎是我的问题所在。检查日期范围时(请参阅下面的实际代码),我该如何避免这种重叠。

实际代码

以下是类似按日期过滤的实际代码。

  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
  }

堆栈

  • Ruby 2.1
  • Rails 3.2
  • PG

问题

如何克服夏令时生效的时间重叠。

1 个答案:

答案 0 :(得分:0)

试试这个解决方案。我认为它应该可以解决你的问题:

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

  if starts.class == String and starts.present?
    starts = Time.zone.parse(starts)
    starts += 1.hour if starts.dst?
    starts = starts.to_datetime
  end

  if ends.class == String and ends.present?      
    ends = Time.zone.parse(ends) + 1.day
    ends += 1.hour if ends.dst?
    ends = ends.to_datetime
  end

  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
}