views:

138

answers:

2

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

A: 

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
Beanish
The questions specifically asks for a gem to streamline the visual representation of this operation (and those like it). This does not really answer his question.
Myrddin Emrys
Do you ever find that the client really doesn't know what he wants (not specifically referring to you, blogofsongs)
glenn jackman
+3  A: 

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]
glenn jackman
Perfect, thanks so much
blogofsongs