What is the best way to calculate the Date, Month, and Year of the next Thursday (or any day) from today in Ruby?
UPDATE In order to create dummy objects, I'm trying to figure out how to calculate a random time. In all, I'd like to produce a random time between 5 and 10 PM on the next Thursday of the week.
date = Date.today
date += 1 + ((3-date.wday) % 7)
# date is now next Thursday
DateTime.now.next_week.next_day(3)
As @Nils Riedemann pointed out:
Keep in mind that it will not get the next thursday, but the thursday of the next week. eg. If tomorrow was thursday, it won't return tomorrow, but next week's thursdays.
Here is an excerpt of some code I've written recently which handles the missing case.
require 'date'
module DateTimeMixin
def next_week
self + (7 - self.wday)
end
def next_wday (n)
n > self.wday ? self + (n - self.wday) : self.next_week.next_day(n)
end
end
# Example
ruby-1.9.3-p194 :001 > x = DateTime.now.extend(DateTimeMixin)
=> #<DateTime: 2012-10-19T15:46:57-05:00 ... >
ruby-1.9.3-p194 :002 > x.next_week
=> #<DateTime: 2012-10-21T15:46:57-05:00 ... >
ruby-1.9.3-p194 :003 > x.next_wday(4)
=> #<DateTime: 2012-10-25T15:46:57-05:00 ... >
Aside from getting next Thursday as the others described, Ruby provides easy methods to get the month and year from any date:
month = date.month
year = date.year
Inside of Rails you can easily get next Thursday as such:
next_thur = Date.today.next_week.advance(:days=>3)
UPDATE
Thanks to @IvanSelivanov in the comments for pointing this out. You can skip a step by doing:
next_thur = Date.today.next_week(:thursday)
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