如何在铁路选定的月份和年份中获得特定周的疲软日子?

时间:2015-06-16 12:58:27

标签: ruby-on-rails week-number

我希望在选定的年份和月份中获得特定一周的所有疲软日子。我在控制器中获取了year= 2015, month= 6 ,and weeknumber = 2这样的数据。如何在rails中获取这些特定数据的工作日?

我想要一个像这样的方法,通过取周数来输出工作日。但周数应该是那个月,应该小于或等于五。下面的代码输出全年的周数。

require 'date'

def week_dates( week_num )
year = Time.now.year
week_start = Date.commercial( year, week_num, 1 )
week_end = Date.commercial( year, week_num, 7 )
week_start.strftime( "%m/%d/%y" ) + ' - ' +        week_end.strftime("%m/%d/%y" )
end

puts week_dates(22)

1 个答案:

答案 0 :(得分:1)

由于您使用的是rails,因此您可以使用beginning_of_weekend_of_week的有效支持方法here来执行此操作

# first week in June
d = Date.new(2015,6, 1)
# => Mon, 01 Jun 2015

# add a week to get the second week
d += 1.week
# => Mon, 08 Jun 2015

(d.beginning_of_week..d.end_of_week).to_a
#=> [Mon, 08 Jun 2015, Tue, 09 Jun 2015, Wed, 10 Jun 2015, Thu, 11 Jun 2015, Fri, 12 Jun 2015, Sat, 13 Jun 2015, Sun, 14 Jun 2015]

如果你希望你的星期在周日开始,你可以这样做,通过一周的开始日期:

(d.beginning_of_week(:sunday)..d.end_of_week(:sunday)).to_a
#=> [Sun, 31 May 2015, Mon, 01 Jun 2015, Tue, 02 Jun 2015, Wed, 03 Jun 2015, Thu, 04 Jun 2015, Fri, 05 Jun 2015, Sat, 06 Jun 2015]