From: Yossef Mendelssohn Date: 2007-09-26T23:37:02+09:00 Subject: Re: Finding the last Sunday of a month On Sep 26, 9:10 am, Dale Martenson wrote: > On Sep 26, 9:00 am, Yossef Mendelssohn wrote: > > > > > On Sep 26, 8:44 am, Peter Bailey 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) > > => # > > irb(main):003:0> d.to_s > > => "2007-02-01" > > irb(main):004:0> d -= 1 > > => # > > irb(main):005:0> d.to_s > > => "2007-01-31" > > irb(main):006:0> d -= d.wday > > => # > > 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. > > I think using -1 as the day of month gets you the last day of the > month. > > irb(main):002:0> d = Date.new(2007, 1, -1) > => # > irb(main):003:0> d.to_s > => "2007-01-31" > irb(main):004:0> (d - d.wday).to_s > => "2007-01-28" > > --Dale Hey, you're right! At least that seems to work. Thanks! (Note: Getting this from you is apparently easier than reading the documentation for Date.new (really Date.civil), which says "m and d can be negative, in which case they count backwards from the end of the year and the end of the month respectively.") -- -yossef