Class: Pdfrb::Model::Date

Inherits:
Object
  • Object
show all
Defined in:
lib/pdfrb/model/date.rb

Overview

PDF date (s7.9.4): D:YYYYMMDDHHmmSSOHH'mm' string. Immutable value object wrapping a Time.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(time) ⇒ Date

Returns a new instance of Date.



18
19
20
21
# File 'lib/pdfrb/model/date.rb', line 18

def initialize(time)
  @time = time
  freeze
end

Instance Attribute Details

#timeObject (readonly)

Returns the value of attribute time.



16
17
18
# File 'lib/pdfrb/model/date.rb', line 16

def time
  @time
end

Class Method Details

.format(time) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/pdfrb/model/date.rb', line 52

def self.format(time)
  off = time.utc_offset
  sign = off >= 0 ? "+" : "-"
  aoff = off.abs
  oh = aoff / 3600
  om = (aoff % 3600) / 60
  "D:%04d%02d%02d%02d%02d%02d%s%02d'%02d'" % [
    time.year, time.month, time.day, time.hour, time.min, time.sec,
    sign, oh, om
  ]
end

.parse(str) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/pdfrb/model/date.rb', line 23

def self.parse(str)
  return new(str) if str.is_a?(::Time)
  return nil if str.nil?
  return nil if str.is_a?(::String) && str.empty?

  unless str.is_a?(::String) && (m = REGEX.match(str))
    raise Pdfrb::ParseError, "invalid PDF date: #{str.inspect}"
  end

  sign = m[7]
  utc_offset =
    if sign.nil? || sign == "Z"
      0
    else
      mul = sign == "-" ? -1 : 1
      (m[8].to_i * 3600 + m[9].to_i * 60) * mul
    end

  ::Time.new(
    m[1].to_i,
    m[2] ? m[2].to_i.clamp(1, 12) : 1,
    m[3] ? m[3].to_i.clamp(1, 31) : 1,
    m[4].to_i.clamp(0, 23),
    m[5].to_i.clamp(0, 59),
    m[6].to_i.clamp(0, 59),
    utc_offset
  )
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



68
69
70
71
72
73
74
# File 'lib/pdfrb/model/date.rb', line 68

def ==(other)
  case other
  when Date then @time == other.time
  when ::Time then @time == other
  else false
  end
end

#hashObject



77
78
79
# File 'lib/pdfrb/model/date.rb', line 77

def hash
  @time.hash
end

#to_sObject



64
65
66
# File 'lib/pdfrb/model/date.rb', line 64

def to_s
  self.class.format(@time)
end