module ExcelDatediff::Core

Constants

DIFF_TYPES

Public Instance Methods

datedif(starting_date, ending_date, diff_type = :d) click to toggle source
# 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

Private Instance Methods

normalize_dates(sd, ed) click to toggle source
# File lib/excel_datediff/core.rb, line 36
def normalize_dates(sd, ed)
  starting_date, ending_date = sd.to_date, ed.to_date
  raise ExcelDatediff::Error, "Invalid date difference !" if ending_date < starting_date

  [starting_date, ending_date]
end
normalize_diff_type(diff_type) click to toggle source
# File lib/excel_datediff/core.rb, line 29
def normalize_diff_type(diff_type)
  dt = diff_type.to_s.downcase.to_sym
  raise ExcelDatediff::Error, "Invalid date diff type: '#{diff_type}'" unless DIFF_TYPES.include? dt

  dt
end