quarters snippets

Calculating quarters in Ruby

Tagged quarters, ruby  Languages ruby
class Date
  def quarter
    case self.month
    when 1,2,3 then 1
    when 4,5,6 then 2
    when 7,8,9 then 3
    when 10,11,12 then 4
    end
  end

  def start_of_previous_quarter
    end_of_previous_quarter.start_of_quarter
  end

  def end_of_previous_quarter
    start_of_quarter.prev_day
  end

  def start_of_quarter
    first_month = [10, 7, 4, 1].detect { |m| m <= self.month }
    Date.new(self.year, first_month, 1)
  end

  def end_of_quarter
    last_month = [3, 6, 9, 12].detect { |m| m >= self.month }
    Date.new(self.year, last_month, 1).next_month.prev_day
  end
end

Example:

now = Date.parse('2015-06-01')
now.start_of_quarter => 2015-04-01
now.end_of_quarter => 2015-06-30
now.start_of_previous_quarter => 2015-01-01
now.end_of_previous_quarter => 2015-03-31