Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails - Get the previous Friday? (Friday of last week)

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:

  • Saturday, March 4th through Friday, March 10th -> Friday, March 3rd
  • Saturday, March 11th through Friday, March. 17th -> Friday, March 10th
like image 406
Greg Blass Avatar asked Mar 31 '17 20:03

Greg Blass


1 Answers

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
like image 77
moveson Avatar answered Oct 05 '22 23:10

moveson