I have a date and i want to find out the months of that particular quarter.How can i have this done in ruby in the easiest possible way? I mean if the date i give is 27-04-2011
, then the result i must get is April, May,June as string or int like 4,5,6 for April to June.
You can define a function for that to accept the date
as argument and return the quarter
def current_quarter_months(date)
quarters = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
quarters[(date.month - 1) / 3]
end
The function will return array based on the the value of the quarter the date belongs to.
You can get the quarter from any date by doing this:
quarter = (((Date.today.month - 1) / 3) + 1).to_i
Or even shorter:
quarter = (Date.today.month / 3.0).ceil
You can do the following:
m = date.beginning_of_quarter.month
"#{m},#{m+1},#{m+2}"
as in
>> date=Date.parse "27-02-2011"
=> Sun, 27 Feb 2011
>> m = date.beginning_of_quarter.month
=> 1
>> "#{m},#{m+1},#{m+2}"
=> "1,2,3"
You can define a function for that to accept the date
as argument and return the quarter
def current_quarter_months(date)
quarters = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
quarters[(date.month - 1) / 3]
end
The function will return array based on the the value of the quarter the date belongs to.
For ones who have come here by searching "ruby date quarter". You can easily extend Date class with quarters:
class Date
def quarter
case self.month
when 1,2,3
return 1
when 4,5,6
return 2
when 7,8,9
return 3
when 10,11,12
return 4
end
end
end
Usage example:
Date.parse("1 jan").quarter # -> 1
Date.parse("1 apr").quarter # -> 2
Date.parse("1 jul").quarter # -> 3
Date.parse("1 oct").quarter # -> 4
Date.parse("31 dec").quarter # -> 4
The way your question is worded you can just use the #month
"then the result i must get is April, May,June as string or int like 4,5,6 for April to June."
April is month 4 so
d = Date.parse('2014-04-01')
=> Tue, 01 Apr 2014
d.month
=> 4
If you really want the quarter, you can open up the date class and add your own quarter method
class Date
def quarter
(month / 3.0).ceil
end
end
Example Usage
d = Date.parse('2014-04-01')
=> Tue, 01 Apr 2014
d.quarter
=> 2
d.quarter
should return 2 not 4 –
Prizewinner Date
with quarter
is a really nice way to go when you're dealing with quarters all the time. Just make sure to leave copious notes so everybody knows it's there. :) –
Cobbett Date#quarter (Rails 7.1+)
Starting from Rails 7.1, there is a quarter method.
Date.new(2010, 1, 31).quarter # => 1
Date.new(2010, 4, 12).quarter # => 2
Date.new(2010, 9, 15).quarter # => 3
Date.new(2010, 12, 25).quarter # => 4
So now, to get the quarter is as simple as this:
Date.parse("27-04-2011").quarter
# => 2
Sources:
Notes:
© 2022 - 2024 — McMap. All rights reserved.