Sha256: cb930d7d5a69022687b0c1aa332c17022d0a19d34fcf72271ae01fc0db53382b

Contents?: true

Size: 955 Bytes

Versions: 3

Compression:

Stored size: 955 Bytes

Contents

module QueryFilter
  module Utils
    class DateNormalizer
      TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
      PG_MIN_YEAR = -4713
      PG_MAX_YEAR = 294276

      attr_reader :date, :format

      def initialize(date, format)
        @date = date
        @format = format
        @parsed_value = parse
      end

      def normalize
        valid?(@parsed_value) ? @parsed_value : default_date
      end

      private

      def date?
        date.is_a?(Time) || date.is_a?(DateTime)
      end

      def valid?(value)
        return false unless Date.valid_date?(value.year, value.month, value.day)

        value.year > PG_MIN_YEAR && value.year < PG_MAX_YEAR
      end

      def parse
        return date if date?

        time = DateTime.strptime(date, format)
        Time.zone.parse(time.strftime(TIME_FORMAT))
      rescue StandardError => _e
        default_date
      end

      def default_date
        Time.zone.today
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
query_filter-0.1.8 lib/query_filter/utils/date_normalizer.rb
query_filter-0.1.7 lib/query_filter/utils/date_normalizer.rb
query_filter-0.1.6 lib/query_filter/utils/date_normalizer.rb