我将如何计算日期的季度开始/结束日期?例如,如果我给出"2012-10-11"
我想要的方法:{ :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
ActiveSupportbeginning_of_quarter
仅为此提供end_of_quarter
:
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
像这样的东西应该工作:
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
为了帮助您理解,请参阅以下内容:
(1..12).map { |month| month - (month - 1) % 3 }
#=> [1, 1, 1, 4, 4, 4, 7, 7, 7, 10, 10, 10]
日期的运算符>>
将在n
几个月后返回日期,- 1
并将返回前一天的日期。
使用此处提供的季度日期范围:http ://en.wikipedia.org/wiki/Calendar_year
- 第一季度:1月初至3月底
- 第二季度:4月初至6月底
- 第三季度:7月初至9月底
- 第四季度:10月初至12月底
一个简单的解决方案将使用如下逻辑:
# Is today's date in Q4?
(Date.parse('2012-10-01')..Date.parse('2012-12-31')).cover?(Date.today)
按照这个逻辑:
def quarter_dates(date = Date.today)
4.times do |i|
start = Date.parse("#{date.year}-#{i*3+1}-01")
if (start..(start >> 3 - 1)).cover?(date)
return {
:begin_date => start,
:end_date => (start >> 3) - 1
}
end
end
end
有些地方有点脏,但我认为它应该给你一个良好的开端。