Method: NHKore::DatetimeParser.parse_range

Defined in:
lib/nhkore/datetime_parser.rb

.parse_range(value) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/nhkore/datetime_parser.rb', line 73

def self.parse_range(value)
  # Do not use unspace_web_str(), want spaces for formats.
  value = Util.strip_web_str(Util.reduce_space(value))
  values = value.split('...',2)

  return nil if values.empty? # For '' or '...'

  # For '2020...' or '...2020'.
  if value.include?('...')
    # values.length is always 2 because of 2 in split() above.

    # For '2020...'.
    if Util.empty_web_str?(values[1])
      values[1] = :infinity
    # For '...2020'.
    elsif Util.empty_web_str?(values[0])
      values[0] = :infinity
    end
  end

  datetimes = [
    DatetimeParser.new, # "From" date time
    DatetimeParser.new, # "To" date time
  ]

  values.each_with_index do |v,i|
    dt = datetimes[i]

    # Minimum/Maximum date time for '2020...' or '...2020'.
    if v == :infinity
      # "From" date time.
      if i == 0
        dt.min!
      # "To" date time.
      else
        dt.max!
      end
    else
      v = Util.strip_web_str(v)

      FMTS.each_with_index do |fmt,j|
        # If don't do this, "%d" values will be parsed using "%d %H".
        # It seems as though strptime() ignores space.
        raise ArgumentError if fmt.include?(' ') && !v.include?(' ')

        # If don't do this, "%y..." values will be parsed using "%d...".
        raise ArgumentError if fmt.start_with?('%d') && v.split(' ')[0].length > 2

        dt.parse!(v,fmt)

        break # No problem; this format worked
      rescue ArgumentError
        # Out of formats.
        raise if j >= (FMTS.length - 1)
      end
    end
  end

  from = datetimes[0]
  to = datetimes[1]

  from.autofill!(:from,to)
  to.autofill!(:to,from)

  return [from.jst_time,to.jst_time]
end