获取特定工作日的最接近日期 [英] Get the closest date of a specific week day
本文介绍了获取特定工作日的最接近日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有个约会,例如,我想找到最近的星期四.尽管我希望它可以在任何工作日工作,而不仅仅是星期四.
I have a date and I want to find the closest Thursday for instance. Though I want it to work for any week day, not just Thursday.
为避免混淆,我不希望下一个星期四,我想要上一个或下一个星期四,以最近的一个为准.因此它必须是双向的.
To avoid confusion, I don't want the next Thursday, I want either the previous or next Thursday, whichever is the closest. So it has to be bidirectional.
我已经写了一个能做到这一点的代码,但是我显然对while循环感到不满意,我想知道你们是否对更好的实现有一个想法.
I have written a code that does it but I'm clearly not happy with the while loop and I was wondering if you guys had an idea of a better implementation.
def closest_date(date, wday)
# already ok
return date if date.wday == wday
before_date = date
after_date = date
until before_date.wday == wday && after_date.wday == wday
before_date -= 1.day unless before_date.wday == wday
after_date += 1.day unless after_date.wday == wday
end
if (date - before_date).to_i > (after_date - date).to_i
return after_date
else
return before_date
end
end
推荐答案
这就是我要做的:
def closest_day(weekday_name,date=Date.today)
distance = Date.parse(weekday_name).cwday - date.cwday
(date + (distance.abs < 4 ? distance : 7 - distance.abs).days)
end
例如, weekday_name
是" thursday
".
这篇关于获取特定工作日的最接近日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文