Topic: Parse date from wday

I am saving a record with a day_number attribute.  I would like to retrieve the earliest date in future with a wday value equal to the day_number.

For example:
I have a record with day_number = 3
I now want to retrieve the next date with wday = 3 (so the next Wednesday)  is.  If today is Wednesday it should return todays date, else next week Wednesday's date.

Any idea how I can accomplish this?

Re: Parse date from wday

Assuming you are in a Rails app, ActiveSupport adds some convenience methods to the Date class. One of them is next_week, which does almost what you want. You could just take that code and hack it a bit...

Re: Parse date from wday

wiehann wrote:

I am saving a record with a day_number attribute.  I would like to retrieve the earliest date in future with a wday value equal to the day_number.

For example:
I have a record with day_number = 3
I now want to retrieve the next date with wday = 3 (so the next Wednesday)  is.  If today is Wednesday it should return todays date, else next week Wednesday's date.

Any idea how I can accomplish this?


def next_date(daynum)
  diff = daynum - Date.today.wday
  diff = 7 + diff if diff < 0
  Date.today + diff.days
end

Feels like there's a more elegant way to get diff.

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams

Re: Parse date from wday

@Max.  Your method is a lot cleaner than what I ended up using.  I used something like this...

send_day = Date.today
send_in_x_days = send_day.wday
if notification.day > send_in_x_days
  send_day += (notification.day - send_in_x_days).days
else
  send_day += ((7 + notification.day) - send_in_x_days).days
end

I'll implement yours when I get home later today though.
Thank you