Nik So
Nik So

Reputation: 16811

How to find the date for the upcoming weekend in Ruby?

so I wanted to have an option called Weekend Delivery, but I can't seem to find any nifty Date#method that can help determine the date (like 2011-09-24) for Saturday, say.

So far I come up with:

today = Date.today
sat = today + (6-today.wday) # 6 being the 6th day of the week with 1 being Monday

Not that it's not short enough, but I thought if there are any built-in or Gem method that does something like Date.this_sat, Date.this_thur, Date.this_weekend, it would be nice..

Thanks!

Upvotes: 0

Views: 177

Answers (2)

Sean
Sean

Reputation: 2891

Use the Chronic gem, it is fantastic!

gem install chronic

Here is an example:

require 'chronic'
Chronic.parse('this Saturday noon')
#=> Sat Sep 24 12:00:00 PDT 2011

I edited the output to reflect the newest gem version since I am using an older version.

Upvotes: 3

steenslag
steenslag

Reputation: 80065

Well, ActiveSupport has an end_of_week method. Subtract 1 and you're there: weekend!

Upvotes: 3

Related Questions