Module: ExcelDatediff::Core

Defined in:
lib/excel_datediff/core.rb

Constant Summary collapse

DIFF_TYPES =
i[d m y md ym yd].freeze

Instance Method Summary collapse

Instance Method Details

#datedif(starting_date, ending_date, diff_type = :d) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/excel_datediff/core.rb', line 7

def datedif(starting_date, ending_date, diff_type = :d)
  diff_type = normalize_diff_type diff_type
  starting_date, ending_date = normalize_dates(starting_date, ending_date)

  years = (ending_date.strftime('%Y%m%d').to_i - starting_date.strftime('%Y%m%d').to_i)/10000.to_i
  months = (ending_date.strftime('%m%d').to_i - starting_date.strftime('%m%d').to_i)/100.to_i
  months = months < 0 ? months+12 : months
  days = ending_date.day - starting_date.day

  case diff_type
  when :y then years
  when :m then years*12 + months +1
  when :d then (ending_date - starting_date).to_i
  when :ym then months
  when :yd then (ending_date - (starting_date >> 12*years)).to_i
  when :md then (days<0 ? ending_date - (starting_date >> 12*years+months) : days).to_i
  end

end