Module: ASE::Time

Defined in:
lib/as-extensions/time.rb

Overview

Ruby Time classes are a mess. This module attempts to restore order by making bold choices. It provides a standard string format and always uses UTC and Epoch.

Constant Summary collapse

DATE_FORMAT =
"%Y-%m-%dT%H:%M:%S"

Class Method Summary collapse

Class Method Details

.epoch(t) ⇒ Object

Converts various times to a number of seconds since Epoch



55
56
57
58
59
60
61
# File 'lib/as-extensions/time.rb', line 55

def epoch(t)
  if t.nil? then epoch(now)
  elsif ( t.is_a?(::Time) || t.is_a?(::Numeric) ) then t.to_i
  elsif t.is_a?(::DateTime) then epoch(to_time(t))
  elsif t.is_a?(::String) then epoch(from_string(t))
  else nil end
end

.from_string(s) ⇒ Object

Convert an ASE time string to a DateTime



44
45
46
# File 'lib/as-extensions/time.rb', line 44

def from_string(s)
  ::Time.parse("#{s}Z")
end

.now(type = nil) ⇒ Object



31
32
33
34
35
36
# File 'lib/as-extensions/time.rb', line 31

def now(type=nil)
  case type
    when :string; 0.seconds.ago.strftime(DATE_FORMAT)
    else 0.seconds.ago
  end
end

.to_string(t) ⇒ Object

Convert various time classes to string



39
40
41
# File 'lib/as-extensions/time.rb', line 39

def to_string(t)
  t.respond_to?(:getutc) ? t.getutc.strftime(DATE_FORMAT) : t.strftime(DATE_FORMAT)
end

.to_time(t) ⇒ Object

Force conversion of a DateTime to a Time



49
50
51
52
# File 'lib/as-extensions/time.rb', line 49

def to_time(t)
  if t.is_a?(::Time) then t
  else from_string(to_string(t)) end
end