Class: Lutaml::Model::Type::Date

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

Constant Summary collapse

TIMEZONE_RE =

Matches timezone suffix in date strings: Z, +HH:MM, -HH:MM

/(Z|[+-]\d{2}:\d{2})\s*$/

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



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/lutaml/model/type/date.rb', line 12

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

  case value
  when ::DateTime
    # Preserve timezone by keeping as DateTime at midnight
    ::DateTime.new(value.year, value.month, value.mday, 0, 0, 0,
                   value.offset)
  when ::Time
    value.to_date
  when ::Date
    value
  else
    str = value.to_s
    tz_match = str.match(TIMEZONE_RE)
    if tz_match
      date = ::Date.parse(str.sub(TIMEZONE_RE, ""))
      offset = parse_timezone(tz_match[1])
      ::DateTime.new(date.year, date.month, date.mday, 0, 0, 0, offset)
    else
      ::Date.parse(str)
    end
  end
rescue ArgumentError
  nil
end

.default_xsd_typeString

Default XSD type for Date

Returns:



55
56
57
# File 'lib/lutaml/model/type/date.rb', line 55

def self.default_xsd_type
  "xs:date"
end

.parse_timezone(offset_str) ⇒ Rational

Parse timezone string to Rational offset (fraction of day)

Parameters:

  • tz (String)

    timezone string (Z, +HH:MM, -HH:MM)

Returns:

  • (Rational)

    offset as fraction of day



63
64
65
66
67
68
69
70
71
# File 'lib/lutaml/model/type/date.rb', line 63

def self.parse_timezone(offset_str)
  return Rational(0) if offset_str == "Z"

  sign = offset_str.start_with?("-") ? -1 : 1
  parts = offset_str.delete("+-").split(":")
  hours = parts[0].to_i
  minutes = parts[1].to_i
  Rational(sign * ((hours * 60) + minutes), 1440)
end

.serialize(value) ⇒ Object

xs:date format with optional timezone



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

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

  case value
  when ::DateTime
    value.strftime("%Y-%m-%d%:z")
  else
    value.iso8601
  end
end