Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby find next Thursday (or any day of the week) [duplicate]

Tags:

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.

like image 953
neon Avatar asked Oct 01 '11 16:10

neon


3 Answers

date = Date.today
date += 1 + ((3-date.wday) % 7)
# date is now next Thursday
like image 79
millimoose Avatar answered Sep 22 '22 21:09

millimoose


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 ... > 
like image 33
Adam Eberlin Avatar answered Sep 23 '22 21:09

Adam Eberlin


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)
like image 32
WattsInABox Avatar answered Sep 22 '22 21:09

WattsInABox