Module: DifferenceCalculator

Defined in:
lib/difference_calculator.rb,
lib/difference_calculator/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.days_in_month(date) ⇒ Object



28
29
30
# File 'lib/difference_calculator.rb', line 28

def self.days_in_month(date)
  Date.new(date.year, date.month, -1).day
end

.difference_in_months(start_date, end_date) ⇒ Object



7
8
9
# File 'lib/difference_calculator.rb', line 7

def self.difference_in_months(start_date, end_date)
  (end_date - start_date).to_f / 365 * 12
end

.exact_month_difference(start_date, end_date) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/difference_calculator.rb', line 11

def self.exact_month_difference(start_date, end_date)
  month_number = -1
  month_diff = difference_in_months(start_date, end_date)

  (month_diff * 2).to_i.times do |month|
    days = days_in_month(end_date)
    actual_date = (end_date - days) + 1
    month_number += 1

    break if start_date.between?(actual_date, end_date)
  end

  return 0 if month_number == -1

  month_number < 4 ? 4 : month_number
end