Ruby on Rails - 获取日期 - 给出的是年,月,周数和日

时间:2016-09-29 18:49:42

标签: ruby-on-rails ruby ruby-on-rails-4

我遇到以下任务的麻烦:

给出以下参数:

Year: 2016
Month: 2
Week of Month: 2
Day of week: Monday

结果应为2016-02-08

有没有办法解决这个问题?

提前致谢

2 个答案:

答案 0 :(得分:0)

这样做的方法是

weekday_index = {monday: 1, tuesday: 2, wednesday: 3, thursday: 4, friday: 5, saturday: 6, sunday: 7}
day_in_a_week = 7
year = year_param # 2016
month = month_param # 8
week_number = 2
day_of_month = (week_number * days_in_a_week) - (days_in_a_week - weekday_index[:monday])
Date.new(year, month, day_of_month).to_s

答案 1 :(得分:0)

您可以使用此代码。使用的值在问题month = 2, week_number = 2year = 2016

中提供
month = 2
year = 2016
week_number = 2
FIRST_DAY = 1 #first day of every month
day = { monday: 1, tuesday: 2, wednesday: 3, thursday: 4, friday: 5, saturday: 6, sunday: 7}

first_wk_of_month = Date.new(year, month, FIRST_DAY).cweek  #=> 05
date_week_num = first_wk_of_month + (week_number - 1)   #=> 06

date = Date.commercial(year, date_week_num, day[:monday]).to_s # 2016-02-08

如果周日开始,一年中有 52 个星期,一个月可以一周低至1天。考虑到这一点,

first_wk_of_month找到有关月份的年份(1到52之间)的周数。

date_week_num查找日期所在年份的实际周数。在这个2月第2周的情景中,它返回6代表一年中的第6周

date_week_numday传递给Date.commercial,我们可以找到date
测试了几天,工作正常。您可以更改变量名称。希望这能解决你的挑战