Module: CMDx::Coercions::DateTime

Extended by:
DateTime
Included in:
DateTime
Defined in:
lib/cmdx/coercions/date_time.rb

Overview

Converts various input types to DateTime format

Handles conversion from date strings, Date objects, Time objects, and other values that can be converted to DateTime using Ruby’s DateTime.parse method or custom strptime formats.

Constant Summary collapse

ANALOG_TYPES =

Types that are already date-time-like and don’t need conversion

%w[Date DateTime Time].freeze

Instance Method Summary collapse

Instance Method Details

#call(value, options = {}) ⇒ DateTime

Converts a value to a DateTime

Examples:

Convert date strings to DateTime

DateTime.call("2023-12-25")               # => #<DateTime: 2023-12-25T00:00:00+00:00>
DateTime.call("Dec 25, 2023")             # => #<DateTime: 2023-12-25T00:00:00+00:00>

Convert with custom strptime format

DateTime.call("25/12/2023", strptime: "%d/%m/%Y")
# => #<DateTime: 2023-12-25T00:00:00+00:00>

Convert existing date objects

DateTime.call(Date.new(2023, 12, 25))     # => #<DateTime: 2023-12-25T00:00:00+00:00>
DateTime.call(Time.new(2023, 12, 25))     # => #<DateTime: 2023-12-25T00:00:00+00:00>

Parameters:

  • value (Object)

    The value to convert to DateTime

  • options (Hash) (defaults to: {})

    Optional configuration parameters

Options Hash (options):

  • :strptime (String)

    Custom date format string for parsing

Returns:

  • (DateTime)

    The converted DateTime value

Raises:

  • (CoercionError)

    If the value cannot be converted to DateTime



40
41
42
43
44
45
46
47
48
# File 'lib/cmdx/coercions/date_time.rb', line 40

def call(value, options = {})
  return value if ANALOG_TYPES.include?(value.class.name)
  return ::DateTime.strptime(value, options[:strptime]) if options[:strptime]

  ::DateTime.parse(value)
rescue TypeError, ::Date::Error
  type = Locale.t("cmdx.types.date_time")
  raise CoercionError, Locale.t("cmdx.coercions.into_a", type:)
end