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(arg) ⇒ Object

Convert a duration to a Time value by considering the duration to be the number of seconds since the epoch



14
15
16
17
18
19
20
21
# File 'lib/ruby_units/time.rb', line 14

def self.at(arg)
  case arg
  when Unit
    unit_time_at(arg.convert_to("s").scalar)
  else
    unit_time_at(arg)
  end
end

.in(duration) ⇒ Object

usage: Time.in ‘5 min’



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

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



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

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

#-(other) ⇒ Object



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

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

#to_dateObject



31
32
33
34
# File 'lib/ruby_units/time.rb', line 31

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



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

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

#unit_addObject



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

alias :unit_add :+

#unit_subObject



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

alias :unit_sub :-