Module: MuchRails::Date

Defined in:
lib/much-rails/date.rb

Constant Summary collapse

InvalidError =
Class.new(TypeError)

Class Method Summary collapse

Class Method Details

.for(value) ⇒ Object

Examples:

MuchRails::Date.for(nil) # => nil
MuchRails::Date.for(" ") # => nil
MuchRails::Date.for(Time.zone.today) # => Date
MuchRails::Date.for(Time.current) # => Date
MuchRails::Date.for(DateTime.current) # => Date
MuchRails::Date.for("07/04/2020") # => Date
MuchRails::Date.for("2020.07.04") # => Date
MuchRails::Date.for("2020-07-04T08:15:00Z") # => Date


17
18
19
20
21
22
23
24
25
26
27
# File 'lib/much-rails/date.rb', line 17

def self.for(value)
  return if value.blank?

  if value.respond_to?(:to_date) && !value.is_a?(::String)
    value.to_date
  else
    parse(value)
  end
rescue
  raise MuchRails::Date::InvalidError, "Invalid Date: #{value.inspect}."
end

.parse(value) ⇒ Object



29
30
31
32
33
# File 'lib/much-rails/date.rb', line 29

def self.parse(value)
  parse_united_states(value)
rescue ArgumentError
  parse8601(value)
end

.parse8601(value) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/much-rails/date.rb', line 43

def self.parse8601(value)
  formatted_value = value.to_s.gsub(/[^\w\s:]/, "-")

  ::Date.iso8601(formatted_value)
rescue ArgumentError
  ::Time.iso8601(formatted_value).utc.to_date
end

.parse_united_states(value) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/much-rails/date.rb', line 35

def self.parse_united_states(value)
  formatted_value = value.to_s.gsub(/[^\w\s:]/, "-")

  ::Date.strptime(formatted_value, "%m-%d-%Y")
rescue ArgumentError
  ::Date.strptime(formatted_value, "%Y-%m-%d")
end