RoR |日期范围不跨越多个月

时间:2012-06-01 00:15:31

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2

我正在尝试为日历创建一个日期数组,其中有一些额外的一天用于下一个月和上一个月将填写一周。

这是我当前尝试获取数组的方法

def calendar
  selected_month = Date.civil((Time.zone.now.year).to_i, (Time.zone.now.month).to_i)

  start_date = selected_month.beginning_of_month
  start_date.sunday? ? start_date : start_date.beginning_of_week.advance(:days => -1)

  end_date = selected_month.end_of_month
  end_date.sunday? ? end_date.advance(:days => 1).end_of_week : end_date

  #only puts 1-30/31 and does not include the extra off set of days from start and end. :( 
  date_range = (start_date..end_date).to_a   
end

问题是只能从1开始并且即使开始和结束日超过该范围,也会到达月末。

我没有嫁给这种获得阵列的方式,所以也许你有一个更好的整体想法?

1 个答案:

答案 0 :(得分:1)

您忘记重新分配start_date和end_date的值。

  start_date = selected_month.beginning_of_month
  start_date = start_date.sunday? ? start_date : start_date.beginning_of_week.advance(:days => -1)

  end_date = selected_month.end_of_month
  end_date = end_date.sunday? ? end_date.advance(:days => 1).end_of_week : end_date