On Sep 26, 8:44 am, Peter Bailey <pbai... / bna.com> wrote:
> Hello,
> I need to find the date for the last Sunday in January, for any year. I
> need this for a budgetary script I'm trying to write. Using the
> Date/Time module, I've done this so far.
>
> require 'date'
> now = DateTime.now
> year = now.year
> d = Date.new(now.year, 1, 31)
> puts d.wday
>
> yields: 3
>
> This tells me that the last day of January is a Wednesday. But, I need
> that last Sunday. Is there a method in 'date' that can give me the date
> of the last Sunday? The last Sundays of each month are the boundaries
> for my company's budget periods.
>
> Thanks,
> Peter
> --
> Posted viahttp://www.ruby-forum.com/.

Not perfect, but something like this:

Cassady:~ yossef$ irb
irb(main):001:0> require 'date'
=> true
irb(main):002:0> d = Date.new(2007, 2, 1)
=> #<Date: 4908265/2,0,2299161>
irb(main):003:0> d.to_s
=> "2007-02-01"
irb(main):004:0> d -= 1
=> #<Date: 4908263/2,0,2299161>
irb(main):005:0> d.to_s
=> "2007-01-31"
irb(main):006:0> d -= d.wday
=> #<Date: 4908257/2,0,2299161>
irb(main):007:0> d.to_s
=> "2007-01-28"
irb(main):008:0> exit
Cassady:~ yossef$ cal 1 2007
    January 2007
 S  M Tu  W Th  F  S
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31


The "secret", as I see it, is getting the last day of the month and
subtracting that date's wday from it.

Note that I start by getting the first day of the next month and going
back one day. I'm not sure about a sure-fire way to always get the
last day of a month by going forward (because you can get errors
trying to hit the 31st of September), but going back one day from the
first of the next month should work just fine.

--
-yossef