Class: Lutaml::Model::Type::DateTime

Inherits:
Value
  • Object
show all
Defined in:
lib/lutaml/model/type/date_time.rb

Overview

Date and time representation

Constant Summary

Constants inherited from Value

Value::EMPTY_OPTIONS

Instance Attribute Summary

Attributes inherited from Value

#value

Class Method Summary collapse

Methods inherited from Value

format_type_serializer_for, from_format, #initialize, #initialized?, register_format_to_from_methods, register_format_type_serializer, #to_s

Methods included from Xml::Type::Configurable

included

Methods included from UninitializedClassGuard

#cast, #serialize

Constructor Details

This class inherits a constructor from Lutaml::Model::Type::Value

Class Method Details

.cast(value, _options = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/lutaml/model/type/date_time.rb', line 10

def self.cast(value, _options = {})
  return super if Utils.uninitialized?(value)
  return nil if value.nil?

  # If already a DateTime type wrapper, return as-is
  return value if value.is_a?(self)

  case value
  when ::DateTime then value
  when ::Time then value.to_datetime
  else ::DateTime.parse(value.to_s)
  end
rescue ArgumentError
  nil
end

.default_xsd_typeString

Default XSD type for DateTime

Returns:



54
55
56
# File 'lib/lutaml/model/type/date_time.rb', line 54

def self.default_xsd_type
  "xs:dateTime"
end

.format_datetime_iso8601(datetime) ⇒ String

Format DateTime as ISO8601 string preserving fractional seconds and timezone offset. Keeps up to 6 decimal places, strips trailing zeros beyond 3.

Parameters:

  • datetime (DateTime)

    the DateTime to format

Returns:

  • (String)

    ISO8601 formatted string, e.g. “2024-01-01T12:00:00.123+08:00”



40
41
42
43
44
45
46
47
48
49
# File 'lib/lutaml/model/type/date_time.rb', line 40

def self.format_datetime_iso8601(datetime)
  if datetime.sec_fraction.zero?
    datetime.iso8601
  else
    # iso8601(6) produces exactly 6 decimal places
    # e.g. 0.5s -> "0.500000", 0.123456s -> "0.123456"
    # Strip trailing zeros beyond 3 decimal places: ".500000" -> ".500"
    datetime.iso8601(6).sub(/(\.\d{3})0{3}([+-])/, '\1\2')
  end
end

.serialize(value) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/lutaml/model/type/date_time.rb', line 26

def self.serialize(value)
  return nil if value.nil?

  dt = cast(value)
  return nil unless dt

  format_datetime_iso8601(dt)
end