root/lang/ruby/date_time-duration/lib/date_time/duration.rb @ 3656

Revision 3656, 0.9 kB (checked in by walf443, 5 years ago)

lang/ruby/date_time-duration: fixed for date_time-smart.

Line 
1require 'date'
2# SYNOPSYS
3#   dt = DateTime.new(2007, 12, 25)
4#   birth = DateTime.new(1984, 12, 26)
5#   dur = DaTeTime::Duration.new(birth, dt)
6#   dur.years.to_i  # => 22
7class DateTime::Duration
8  def initialize from, to
9    @flag = ( from <= to ) ? 1 : -1
10    @from, @to = ( from <= to ) ? [from, to] : [ to, from ]
11    @duration = to.ajd - from.ajd
12  end
13
14  # It doesn't care about leap seconds.
15  def seconds
16    @duration * 24 * 60 * 60
17  end
18
19  def minutes
20    @duration * 24 * 60
21  end
22
23  def hours
24    @duration * 24
25  end
26
27  def days
28    @duration
29  end
30
31  def weeks
32    @duration / 7
33  end
34
35  # This method return not Rational but Fixnum.
36  def months
37    if @months.nil?
38      i = 0
39      while ( ( @from >> i ) <= @to ) do
40        i += 1
41      end
42
43      @months = ( @flag * ( i - 1 ) )
44    end
45   
46    return @months
47  end
48
49  def years
50    months / 12
51  end
52end
Note: See TracBrowser for help on using the browser.