Ruby/Rails - Get the previous Friday? (Friday of last week)
Here's a way to do it without any conditionals. This will accept a Date, Time, or DateTime object.
def prior_friday(date)
days_before = (date.wday + 1) % 7 + 1
date.to_date - days_before
end
Now you can do any of these:
>> 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
For different days of the week, change the integer added to date.wday
before the mod is applied:
def prior_monday(date)
days_before = (date.wday + 5) % 7 + 1
date.to_date - days_before
end
Or make a universal method:
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
Examples run on Saturday, August 4, 2018:
>> 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
You can use #prev_occurring since Rails 5.2:
Date.today.prev_occurring(:friday)