Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby code to get the date of next Monday (or any day of the week)

Tags:

date

ruby

Given an input of, for example,

day = 'Monday'

how can I calculate the date of the next day?

def date_of_next(day)
  ...
end
like image 300
Panagiotis Panagi Avatar asked Oct 28 '11 14:10

Panagiotis Panagi


3 Answers

require 'date'  def date_of_next(day)   date  = Date.parse(day)   delta = date > Date.today ? 0 : 7   date + delta end  Date.today #=>#<Date: 2011-10-28 (4911725/2,0,2299161)> date_of_next "Monday" #=>#<Date: 2011-10-31 (4911731/2,0,2299161)> date_of_next "Sunday" #=>#<Date: 2011-10-30 (4911729/2,0,2299161)> 
like image 128
fl00r Avatar answered Sep 24 '22 10:09

fl00r


For anyone like me who came here looking for a solution in Rails to this problem, as of Rails 5.2 there is a much easier method to do this.

For anyone (like the original poster) not specifically using Rails, this functionality is available in the ActiveSupport gem.

To find the next occurring day of a week, we can simply write something like Date.today.next_occurring(:friday).

See the documentation for more details.

like image 34
s_dolan Avatar answered Sep 21 '22 10:09

s_dolan


I know this is an old post, but I came up with a couple of methods to quickly get the previous and next day of the week.

# date is a Date object and day_of_week is 0 to 6 for Sunday to Saturday

require 'Date'

def get_next_day(date, day_of_week)
  date + ((day_of_week - date.wday) % 7)
end

def get_previous_day(date, day_of_week)
  date - ((date.wday - day_of_week) % 7)
end

puts today = Date.today
# 2015-02-24

puts next_friday = get_next_day(today, 5)
# 2015-02-27

puts last_friday = get_previous_day(today, 5)
# 2015-02-20
like image 42
Devin Brown Avatar answered Sep 22 '22 10:09

Devin Brown