Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get quarter's begin/end dates

Tags:

date

ruby

How would I calculate a date's quarter begin/end dates? If example if I give the method "2012-10-11" I would like back: { :begin_date => '2012-10-01', :end_date => '2012-12-31' }

def quarter_dates(date = Date.today)
  # TODO...
  return {
    :begin_date => begin_date,
    :end_date => end_date
  }
end
like image 818
Kyle Decot Avatar asked May 04 '26 16:05

Kyle Decot


2 Answers

ActiveSupport provides beginning_of_quarter and end_of_quarter for just this:

require 'active_support/core_ext/date/calculations'

def quarter_dates(date = Date.today)
  {
    begin_date: date.beginning_of_quarter,
    end_date: date.end_of_quarter
  }
end
like image 147
KARASZI István Avatar answered May 06 '26 06:05

KARASZI István


Something like this should work :

def quarter_dates(date = Date.today)
  start_month = date.month - (date.month - 1) % 3
  start_date  = Date.new(date.year, start_month, 1)

  {
    :begin_date => start_date,
    :end_date   => (start_date >> 3) - 1
  }
end

To help you understand, see this bit :

(1..12).map { |month| month - (month - 1) % 3 }
#=> [1, 1, 1, 4, 4, 4, 7, 7, 7, 10, 10, 10]

The operator >> on a date will return the date n months later and the - 1 will return the date one day before.

like image 41
tomferon Avatar answered May 06 '26 05:05

tomferon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!