AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

How to get day of the week next week?

I tried something like...

<%= Date.current.next_week.monday %>
<%= Date.current.next_week.tuesday %>
<%= Date.current.next_week.wednesday %>
<%= Date.current.next_week.thursday %>
<%= Date.current.next_week.friday %>

Getting error: ActionView::Template::Error (undefined method 'tuesday' for Mon, 17 Apr 2017:Date):

So as of today's date the dates would be...

Apr 17
Apr 18
Apr 19
Apr 20
Apr 21

--

Not duplicate (I don't think). I tried those answers. I was unable to render the appropriate days in the view.

Upvotes: 1

Views: 1507

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54223

If you ever need it in plain Ruby, here's a simple way to get it:

  • date minus cwday (day of calendar week) gives you "last sunday"
  • "Last sunday + 8" gives you "next monday".

require 'date'

def next_week(date, day = :monday)
  days = %w(monday tuesday wednesday thursday friday saturday sunday)
  date - date.cwday + 8 + days.index(day.to_s.downcase).to_i
end

puts next_week(Date.today)
# 2017-04-17
puts next_week(Date.today, :friday)
# 2017-04-21
puts next_week(Date.new(2017,4,16))
# 2017-04-17
puts next_week(Date.new(2017,4,17))
# 2017-04-24

For your question, you could use:

next_monday = next_week(Date.today)
puts working_days_next_week = Array.new(5){ |i| next_monday + i }
# 2017-04-17
# 2017-04-18
# 2017-04-19
# 2017-04-20
# 2017-04-21

Upvotes: 1

gwcodes
gwcodes

Reputation: 5690

Your syntax for next_week needs tweaking:

# Works
<%= Date.current.next_week(:tuesday) %>

To understand why your original approach doesn't work: monday and sunday just happen to be defined on DateAndTime::Calculations, but the other days of the week are not.

Upvotes: 3

Related Questions