Class: Time

Inherits:
Object show all
Defined in:
lib/ruby_units/time.rb

Overview

Time math is handled slightly differently. The difference is considered to be an exact duration if the subtracted value is in hours, minutes, or seconds. It is rounded to the nearest day if the offset is in years, decades, or centuries. This leads to less precise values, but ones that match the calendar better.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.at(*args) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/ruby_units/time.rb', line 12

def self.at(*args)
  if Unit === args[0]
    unit_time_at(args[0].to("s").scalar)
  else
    unit_time_at(*args)
  end
end

.in(duration) ⇒ Object

usage: Time.in ‘5 min’



51
52
53
# File 'lib/ruby_units/time.rb', line 51

def self.in(duration)
  Time.now + duration.to_unit
end

.unit_time_atObject



9
# File 'lib/ruby_units/time.rb', line 9

alias unit_time_at at

Instance Method Details

#+(other) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/ruby_units/time.rb', line 34

def +(other)
  case other
  when Unit
    other = other.to('d').round.to('s') if ['y', 'decade', 'century'].include? other.units  
    begin
      unit_add(other.to('s').scalar)
    rescue RangeError
      self.to_datetime + other
    end
  when DateTime
    unit_add(other.to_time)
  else
    unit_add(other)
  end
end

#-(other) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/ruby_units/time.rb', line 57

def -(other)
  case other
  when Unit
    other = other.to('d').round.to('s') if ['y', 'decade', 'century'].include? other.units  
    begin
      unit_sub(other.to('s').scalar)
    rescue RangeError
      self.send(:to_datetime) - other
    end
    
  when DateTime
    unit_sub(other.to_time)
  else
    unit_sub(other)
  end
end

#to_dateObject



28
29
30
31
# File 'lib/ruby_units/time.rb', line 28

def to_date
  x=(Date.civil(1970,1,1)+((self.to_f+self.gmt_offset)/86400.0)-0.5)
  Date.civil(x.year, x.month, x.day)
end

#to_unit(other = nil) ⇒ Object Also known as: unit, u



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

def to_unit(other = nil)
  other ? Unit.new(self).to(other) : Unit.new(self)
end

#unit_addObject



25
# File 'lib/ruby_units/time.rb', line 25

alias :unit_add :+

#unit_subObject



55
# File 'lib/ruby_units/time.rb', line 55

alias :unit_sub :-