有没有办法在Rails中获得上周五的约会?我已经看到了如何获得最接近的星期五,或者上周一或周日,但我特别需要上周五。
所以直到本周的周五,也就是上周五的周五。然后从星期六开始,这是前一天的星期五。
例如:
答案 0 :(得分:8)
这是一种没有任何条件的方法。这将接受Date,Time或DateTime对象。
def prior_friday(date)
days_before = (date.wday + 1) % 7 + 1
date.to_date - days_before
end
现在你可以做以下任何一件事:
>> prior_friday(Date.today)
=> Fri, 24 Mar 2017
>> prior_friday(Date.tomorrow)
=> Fri, 31 Mar 2017
>> prior_friday(Date.new(2017,4,4))
=> Fri, 31 Mar 2017
>> prior_friday(Time.now)
=> Fri, 24 Mar 2017
>> prior_friday(DateTime.tomorrow)
=> Fri, 31 Mar 2017
>> prior_friday(1.year.from_now)
=> Fri, 30 Mar 2018
对于一周中的不同日期,在应用mod之前更改添加到date.wday
的整数:
def prior_monday(date)
days_before = (date.wday + 5) % 7 + 1
date.to_date - days_before
end
或制作通用方法:
def prior_weekday(date, weekday)
weekday_index = Date::DAYNAMES.reverse.index(weekday)
days_before = (date.wday + weekday_index) % 7 + 1
date.to_date - days_before
end
示例在2018年8月4日星期六举行:
>> prior_weekday(Date.today, 'Saturday')
Sat, 28 Jul 2018
>> prior_weekday(Date.today, 'Friday')
Fri, 03 Aug 2018
>> prior_weekday(Date.tomorrow, 'Friday')
Fri, 03 Aug 2018
>> prior_weekday(Date.tomorrow, 'Saturday')
Sat, 04 Aug 2018
>> prior_weekday(Date.tomorrow, 'Sunday')
Sun, 29 Jul 2018
答案 1 :(得分:7)
从Rails 5.2开始,您可以使用#prev_occurring:
Date.today.prev_occurring(:friday)
答案 2 :(得分:0)
试用此扩展程序,您可以将其用作Time.last_friday
或Time.now.last_friday
class Time
def self.last_friday
time = (Time.now - 1.day)
while !time.friday?
time -= 1.day
end
time
end
def last_friday
time = (self - 1.day)
while !time.friday?
time -= 1.day
end
time
end
end
答案 3 :(得分:0)
这就是我想出的。
def prior_weekday(date, index_of_target_day)
if date.wday == index_of_target_day
date - 1.week
else
date - (date.wday - index_of_target_day) % 7
end
end
用法示例:
> MONDAY_INDEX = 1
> prior_weekday(Date.parse('2018-11-16'), MONDAY_INDEX) # 11/16 is a Friday
=> Mon, 12 Nov 2018