Class: ISO8601::Time

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/iso8601/time.rb

Overview

A Time representation

Examples:

t = Time.new('10:11:12')
t = Time.new('T10:11:12.5Z')
t.hour # => 10
t.minute # => 11
t.second # => 12.5
t.zone # => '+00:00'

Constant Summary collapse

FORMAT =
'T%H:%M:%S%:z'
FORMAT_WITH_FRACTION =
'T%H:%M:%S.%2N%:z'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, base = ::Date.today) ⇒ Time

Returns a new instance of Time.

Parameters:

  • input (String)

    The time pattern

  • base (Date) (defaults to: ::Date.today)

    The base date to determine the time



34
35
36
37
38
39
40
# File 'lib/iso8601/time.rb', line 34

def initialize(input, base = ::Date.today)
  @original = input
  @base = base
  @atoms = atomize(input)
  @time = compose(@atoms, @base)
  @second = @time.second + @time.second_fraction.to_f
end

Instance Attribute Details

#atomsObject (readonly)

The original atoms



26
27
28
# File 'lib/iso8601/time.rb', line 26

def atoms
  @atoms
end

#secondObject (readonly)

The second atom



23
24
25
# File 'lib/iso8601/time.rb', line 23

def second
  @second
end

#separatorObject (readonly)

The separator used in the original ISO 8601 string.



20
21
22
# File 'lib/iso8601/time.rb', line 20

def separator
  @separator
end

Instance Method Details

#+(seconds) ⇒ ISO8601::Time

Forwards the time the given amount of seconds.

Parameters:

  • seconds (Numeric)

    The seconds to add

Returns:



47
48
49
50
51
52
# File 'lib/iso8601/time.rb', line 47

def +(seconds)
  moment = @time.to_time.localtime(zone) + seconds
  format = moment.subsec.zero? ? FORMAT : FORMAT_WITH_FRACTION

  ISO8601::Time.new(moment.strftime(format), ::Date.parse(moment.strftime('%Y-%m-%d')))
end

#-(seconds) ⇒ ISO8601::Time

Backwards the date the given amount of seconds.

Parameters:

  • seconds (Numeric)

    The seconds to remove

Returns:



59
60
61
62
63
64
# File 'lib/iso8601/time.rb', line 59

def -(seconds)
  moment = @time.to_time.localtime(zone) - seconds
  format = moment.subsec.zero? ? FORMAT : FORMAT_WITH_FRACTION

  ISO8601::Time.new(moment.strftime(format), ::Date.parse(moment.strftime('%Y-%m-%d')))
end

#to_aObject

Converts self to an array of atoms.



73
74
75
# File 'lib/iso8601/time.rb', line 73

def to_a
  [hour, minute, second, zone]
end

#to_sObject

Converts self to a time component representation.



67
68
69
70
# File 'lib/iso8601/time.rb', line 67

def to_s
  format = @time.second_fraction.zero? ? FORMAT : FORMAT_WITH_FRACTION
  @time.strftime(format)
end