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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With