I have the following date object in Ruby
开发者_如何学PythonDate.new(2009, 11, 19)
How would I find the next Friday?
You could use end_of_week (AFAIK only available in Rails)
>> Date.new(2009, 11, 19).end_of_week - 2
=> Fri, 20 Nov 2009
But this might not work, depending what exactly you want. Another way could be to
>> d = Date.new(2009, 11, 19)
>> (d..(d+7)).find{|d| d.cwday == 5}
=> Fri, 20 Nov 2009
lets assume you want to have the next friday if d is already a friday:
>> d = Date.new(2009, 11, 20) # was friday
>> ((d+1)..(d+7)).find{|d| d.cwday == 5}
=> Fri, 27 Nov 2009
Old question but if you're using rails you can now do the following to get next Friday.
Date.today.sunday + 5.days
Likewise you can do the following to get this Friday.
Date.today.monday + 4.days
d = Date.new(2009, 11, 19)
d+=(5-d.wday) > 0 ? 5 - d.wday : 7 + 5 - d.wday
Rails' ActiveSupport::CoreExtensions::Date::Calculations has methods that can help you. If you're not using Rails, you could just require ActiveSupport.
As Ruby's modulo operation (%) returns positive numbers when your divisor is positive, you can do this:
some_date = Date.new(2009, 11, 19)
next_friday = some_date + (5 - some_date.cwday) % 7
The only issue I can see here is that if some_date
is a Friday, next_friday
will be the same date as some_date
. If that's not the desired behavior, a slight modification can be used instead:
some_date = Date.new(...)
day_increment = (5 - some_date.cwday) % 7
day_increment = 7 if day_increment == 0
next_friday = some_date + day_increment
This code doesn't rely on additional external dependencies, and relies mostly on integer arithmetic.
精彩评论