How to get exact start date and end date of every quarter of a given year in Ruby
I need to get the exact start and end dates (month, day and year) of a given year.
E.g., 2008 Jan. 1, 2008 Mar, 开发者_开发百科30, 2008
Any thoughts on how to do this?
array = [2007, 2008, 2009, 2010]
array.each do |a|
#code to get array of date for a (year)
end
Following thing is more ruby way
array = [2007, 2008, 2009, 2010]
quarters = []
array.each do |a|
@date = Date.parse("1.1.#{a}") unless @date
4.times do
quarters << [@date.beginning_of_quarter, @date.end_of_quarter]
@date = @date.end_of_quarter+1.day
end
end
array = [2007, 2008, 2009, 2010]
quarters = []
array.each do |a|
date = Date.parse("1.1.#{a}")
4.times do
quarters << [date, date+3.month-1.day]
date += 3.month
end
end
quarters
#=> [[Mon, 01 Jan 2007, Sat, 31 Mar 2007], [Sun, 01 Apr 2007, Sat, 30 Jun 2007], [Sun, 01 Jul 2007, Sun, 30 Sep 2007], [Mon, 01 Oct 2007, Mon, 31 Dec 2007], [Tue, 01 Jan 2008, Mon, 31 Mar 2008], [Tue, 01 Apr 2008, Mon, 30 Jun 2008], [Tue, 01 Jul 2008, Tue, 30 Sep 2008], [Wed, 01 Oct 2008, Wed, 31 Dec 2008], [Thu, 01 Jan 2009, Tue, 31 Mar 2009], [Wed, 01 Apr 2009, Tue, 30 Jun 2009], [Wed, 01 Jul 2009, Wed, 30 Sep 2009], [Thu, 01 Oct 2009, Thu, 31 Dec 2009], [Fri, 01 Jan 2010, Wed, 31 Mar 2010], [Thu, 01 Apr 2010, Wed, 30 Jun 2010], [Thu, 01 Jul 2010, Thu, 30 Sep 2010], [Fri, 01 Oct 2010, Fri, 31 Dec 2010]]
if you wanted to get crazy and do it all in one line
[2007, 2008, 2009, 2010].inject([]){|quarters, year| quarters += [1, 4, 7, 10].collect{|month| [Time.parse("#{month}/01/#{year}").beginning_of_quarter, Time.parse("#{month}/01/#{year}").end_of_quarter]}.flatten}
not super expressive, but a cool exercise! I <3 inject
returns:
[Mon Jan 01 00:00:00 -0500 2007, Sat Mar 31 23:59:59 -0400 2007, Sun Apr 01 00:00:00 -0400 2007, Sat Jun 30 23:59:59 -0400 2007, Sun Jul 01 00:00:00 -0400 2007, Sun Sep 30 23:59:59 -0400 2007, Mon Oct 01 00:00:00 -0400 2007, Mon Dec 31 23:59:59 -0500 2007, Tue Jan 01 00:00:00 -0500 2008, Mon Mar 31 23:59:59 -0400 2008, Tue Apr 01 00:00:00 -0400 2008, Mon Jun 30 23:59:59 -0400 2008, Tue Jul 01 00:00:00 -0400 2008, Tue Sep 30 23:59:59 -0400 2008, Wed Oct 01 00:00:00 -0400 2008, Wed Dec 31 23:59:59 -0500 2008, Thu Jan 01 00:00:00 -0500 2009, Tue Mar 31 23:59:59 -0400 2009, Wed Apr 01 00:00:00 -0400 2009, Tue Jun 30 23:59:59 -0400 2009, Wed Jul 01 00:00:00 -0400 2009, Wed Sep 30 23:59:59 -0400 2009, Thu Oct 01 00:00:00 -0400 2009, Thu Dec 31 23:59:59 -0500 2009, Fri Jan 01 00:00:00 -0500 2010, Wed Mar 31 23:59:59 -0400 2010, Thu Apr 01 00:00:00 -0400 2010, Wed Jun 30 23:59:59 -0400 2010, Thu Jul 01 00:00:00 -0400 2010, Thu Sep 30 23:59:59 -0400 2010, Fri Oct 01 00:00:00 -0400 2010, Fri Dec 31 23:59:59 -0500 2010]
A generic one:
def get_dates(year, quarter)
date = Date.new(year, quarter * 3)
[date.beginning_of_quarter, date.end_of_quarter]
end
精彩评论