[英]Given date and day in week, find the closest date in future
假设星期几(假设周一),我需要找到最近的日期(将来)到给定日期(例如9-4-2016),这是一周中的这一天(对于这些例子,它应该是11-4- 2016)。
This is a pure Ruby solution. 这是一个纯Ruby解决方案。
require 'date'
d = Date.strptime('9-4-2016', '%d-%m-%Y')
#=> #<Date: 2016-04-09 ((2457488j,0s,0n),+0s,2299161j)>
d + (1 - d.wday) % 7
#=> #<Date: 2016-04-11 ((2457490j,0s,0n),+0s,2299161j)>
1
is Monday's offset. 1
是周一的偏移量。 d.wday #=> 6
. d.wday #=> 6
。
I have assumed that if the date falls on a Monday, the "closest" Monday is the same day. 我假设如果日期是星期一,那么“最接近的”星期一就是同一天。 If it is to be the following Monday, use:
如果是下周一,请使用:
d + (d.wday == 1) ? 7 : (1 - d.wday) % 7
You can find this date in the nearest week of your date
: 您可以在日期的最近一周找到此
date
:
date = Date.parse('9-4-2016')
(date..date + 6).find {|d| d.strftime("%A") == "Monday"}
#=> Mon, 11 Apr 2016
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.