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.

Instance Method Summary collapse

Instance Method Details

#call(value, options = EMPTY_HASH) ⇒ 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: EMPTY_HASH)

    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

Rbs:

  • (untyped value, ?Hash[Symbol, untyped] options) -> DateTime



35
36
37
38
39
40
41
42
43
# File 'lib/cmdx/coercions/date_time.rb', line 35

def call(value, options = EMPTY_HASH)
  return value.to_datetime if value.respond_to?(:to_datetime)
  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