我想在星期三设定一个至少14天的日期。意思是如果日期是3/14/16,它将设置为3/30/16。如果它是3/10,它也将是3/30。希望使用红宝石。
所以我的想法是这样的:
def next_weds
self + (14 + closest_wed_day)
end
问题是如何定义星期三的含义,如何获得最接近的星期三,然后在该日期添加14。因此,如果今天是星期二,则会增加15.如果是星期四,则会增加20.
答案 0 :(得分:2)
https://github.com/mojombo/chronic/很容易做到这一点。这是你的例子:
Chronic.parse('14 days from now wednesday')
=> 2016-04-20 00:00:00 -0500
答案 1 :(得分:0)
这是一个纯Ruby解决方案。
require 'date'
def first_day_of_week(min_days_from_now, day_of_week)
today = Date.today
days_until_day_of_week = (7 + day_of_week - today.wday) % 7
today + days_until_day_of_week +
7*(([min_days_from_now-days_until_day_of_week, 0].max/7.0).ceil)
end
今天是:
today = Date.today
#=> #<Date: 2016-03-31 ((2457479j,0s,0n),+0s,2299161j)>
wday = today.wday
#=> 4
Date::DAYNAMES[wday]
#=> "Thursday"
假设:
day_of_week = 3
Date::DAYNAMES[day_of_week]
#=> "Wednesday"
然后:
puts " # min_days_from_now date wday"
(0..14).each do |min_days_from_now|
fd = first_day_of_week(min_days_from_now, day_of_week)
puts " # %2d %s %d" % [min_days_from_now, fd.to_s, fd.wday]
end
# min_days_from_now date wday
# 0 2016-04-06 3
# 1 2016-04-06 3
# 2 2016-04-06 3
# 3 2016-04-06 3
# 4 2016-04-06 3
# 5 2016-04-06 3
# 6 2016-04-06 3
# 7 2016-04-13 3
# 8 2016-04-13 3
# 9 2016-04-13 3
# 10 2016-04-13 3
# 11 2016-04-13 3
# 12 2016-04-13 3
# 13 2016-04-13 3
# 14 2016-04-20 3