Question

I can do this myself of course, but is there built-in functionality in Ruby, or a library, that would let me do something like this

date = Time.now
sunday = date.week.first_day
saturday = date.week.last_day

Thanks

Was it helpful?

Solution

Use the ActiveSupport gem. It, however, considers Monday as the start of the week.

require 'active_support'
d = Date.today                     # => Mon, 25 Jan 2010
sun = d.beginning_of_week - 1.day  # => Sun, 24 Jan 2010
sat = d.end_of_week - 1.day        # => Sat, 30 Jan 2010

Needs more work if today is Sunday

def week_ends(date)
  sun = date.beginning_of_week - 1.day
  sat = date.end_of_week - 1.day
  if date.sunday?
    sun += 1.week
    sat += 1.week
  end
  [sun, sat]
end

p d = Date.today
p week_ends(d)

p d = Date.yesterday
p week_ends(d)

results in

Mon, 25 Jan 2010
[Sun, 24 Jan 2010, Sat, 30 Jan 2010]
Sun, 24 Jan 2010
[Sun, 24 Jan 2010, Sat, 30 Jan 2010]

OTHER TIPS

Days are represented by 0..6, Sunday being 0.

date = Time.now
puts date.wday 

would output todays number code of the week.

What are you trying to accomplish?

by adding or subtracting the number of seconds in a day you get to a different date exactly 1 day from now.

date = Time.now
puts date + 86400 #will be tomorrow
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top