Class: ISO8601::DateTime

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

Overview

A DateTime representation

Examples:

dt = DateTime.new('2014-05-28T19:53Z')
dt.year #=> 2014

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(date_time) ⇒ DateTime

Returns a new instance of DateTime.

Parameters:

  • date_time (String)

    The datetime pattern



21
22
23
24
25
# File 'lib/iso8601/date_time.rb', line 21

def initialize(date_time)
  @original = date_time
  @date_time = parse(date_time)
  @second = @date_time.second + @date_time.second_fraction.to_f.round(1)
end

Instance Attribute Details

#secondObject (readonly)

Returns the value of attribute second.



17
18
19
# File 'lib/iso8601/date_time.rb', line 17

def second
  @second
end

Instance Method Details

#+(other) ⇒ Object

Addition

Parameters:

  • other (Numeric)

    The seconds to add



31
32
33
34
35
# File 'lib/iso8601/date_time.rb', line 31

def +(other)
  moment = @date_time.to_time.localtime(zone) + other.to_f.round(1)

  self.class.new(moment.strftime('%Y-%m-%dT%H:%M:%S.%N%:z'))
end

#-(other) ⇒ Object

Substraction

Parameters:

  • other (Numeric)

    The seconds to substract



41
42
43
44
45
# File 'lib/iso8601/date_time.rb', line 41

def -(other)
  moment = @date_time.to_time.localtime(zone) - other.to_f.round(1)

  self.class.new(moment.strftime('%Y-%m-%dT%H:%M:%S.%N%:z'))
end

#==(other) ⇒ Boolean

Parameters:

  • other (#hash)

    The contrast to compare against

Returns:

  • (Boolean)


72
73
74
# File 'lib/iso8601/date_time.rb', line 72

def ==(other)
  (hash == other.hash)
end

#eql?(other) ⇒ Boolean

Parameters:

  • other (#hash)

    The contrast to compare against

Returns:

  • (Boolean)


80
81
82
# File 'lib/iso8601/date_time.rb', line 80

def eql?(other)
  (hash == other.hash)
end

#hashFixnum

Returns:

  • (Fixnum)


86
87
88
# File 'lib/iso8601/date_time.rb', line 86

def hash
  [to_f, self.class].hash
end

#to_aObject Also known as: atoms

Converts DateTime to an array of atoms.



57
58
59
# File 'lib/iso8601/date_time.rb', line 57

def to_a
  [year, month, day, hour, minute, second, zone]
end

#to_fObject

Converts DateTime to a floating point number of seconds since the Epoch.



64
65
66
# File 'lib/iso8601/date_time.rb', line 64

def to_f
  to_time.to_f
end

#to_sObject

Converts DateTime to a formated string



49
50
51
52
53
# File 'lib/iso8601/date_time.rb', line 49

def to_s
  second_format = format((second % 1).zero? ? '%02d' : '%04.1f', second)

  format("%04d-%02d-%02dT%02d:%02d:#{second_format}#{zone}", *atoms)
end