Is there a way to get the previous Friday's date in Rails? I've seen ways to get the closest Friday, or the previous Monday or Sunday, but I specifically need the last Friday.
So up until and including Friday of this current week, it'd be the previous week's Friday. Then starting on Saturday, it'd be the Friday a day before.
For example:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With