将日期范围缩小到每月最后几天的数组?

时间:2014-01-07 16:49:37

标签: ruby arrays date-range

我有一个Ruby日期范围:range = Date.parse("February 1, 2013")..Date.parse("January 15, 2014")

如果您执行range.to_a并将其转换为数组,则会获得该范围内每一天的数组项。

我想要的是每个月最后一天的数组。

基本上类似于:[2013-02-28, 2013-03-31, 2013-04-30, ..., 2013-12-31, 2014-01-31]

3 个答案:

答案 0 :(得分:4)

这是一种不同的方式:

range = Date.parse("February 1, 2013")..Date.parse("January 15, 2014")
range.to_a.map {|date| Date.new(date.year,date.month,1)}.uniq.map {|date| date.next_month.prev_day}

或换句话说:

对于数组中的每个日期

  1. 将day元素设为1,以找到每个月的第一个...
  2. 使该集合唯一,因此每月只有一个元素......
  3. 为每个值添加一个月......
  4. 减去一天。

答案 1 :(得分:0)

require 'date'
COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def days_in_month(month, year = Time.now.year)
   return 29 if month == 2 && Date.gregorian_leap?(year)
   COMMON_YEAR_DAYS_IN_MONTH[month]
end

range = Date.parse("February 1, 2013")..Date.parse("January 15, 2014")
last_year = range.last.year
last_month = range.last.month
last_day =  Time.new(last_year, last_month, days_in_month(last_month, last_year)).to_date

range.select { |d| d.day == days_in_month(d.month, d.year) }.push(last_day).map(&:to_s)
 # => ["2013-02-28", "2013-03-31", "2013-04-30", "2013-05-31", "2013-06-30", "2013-07-31", "2013-08-31", "2013-09-30", "2013-10-31", "2013-11-30", "2013-12-31", "2014-01-31"]

答案 2 :(得分:0)

负日期倒数,因此-1是该月的最后一天:

require 'date'

def last_days_of_months(year=Date.today.year)
  (1..12).map{|month| Date.new(year, month, -1)}
end

puts last_days_of_months

输出:

2014-01-31
2014-02-28
2014-03-31
2014-04-30
2014-05-31
2014-06-30
2014-07-31
2014-08-31
2014-09-30
2014-10-31
2014-11-30
2014-12-31