如何在Ruby中获取给定年份每个季度的确切开始日期和结束日期

时间:2010-04-20 10:55:50

标签: ruby-on-rails ruby

我需要获得给定年份的确切开始和结束日期(月,日和年)。

,例如,2008年 2008年1月1日 2008年3月30日

关于如何做到这一点的任何想法?

array = [2007, 2008, 2009, 2010]

array.each do |a|

   #code to get array of date for a (year)   
end

4 个答案:

答案 0 :(得分:3)

以下事情更为红宝石

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

答案 1 :(得分:1)

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]]

答案 2 :(得分:1)

如果你想变得疯狂并在一行中完成所有这些

[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}

不是超级表现力,而是一种很酷的运动!我&lt; 3注入

返回:

[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]

答案 3 :(得分:1)

通用的一个:

def get_dates(year, quarter)
    date = Date.new(year, quarter * 3)

    [date.beginning_of_quarter, date.end_of_quarter]
end