From: "David A. Black" Date: 2005-08-30T02:21:44+09:00 Subject: Re: Date problem. Hi -- On Tue, 30 Aug 2005, Joe Cheng wrote: > ober wrote: > >> I have read over the man pages and can not seem to find a way to do the >> following >> >> -----php--------------- >> $lastmonth = mktime(0, 0, 0, date("m")-1, date(01), date("Y")); >> $name = date('Y-m-d', $lastmonth); >> echo "$name\n"; >> ----php---------------- >> >> Where the first day of the previous month is listed. >> In this case you would get 2005-07-01 > > A literal translation to Ruby: > lastmonth = Date.new(Date.today.year, Date.today.month - 1) > name = lastmonth.to_s > puts name > > However, this will give you the wrong answer in January. Here's one that > accounts for January: > > year, lastmonth = Date.today.year, Date.today.month - 1 > year, lastmonth = year - 1, 12 if lastmonth == 0 > puts Date.new(year, lastmonth).to_s I think my answer probably suffered from the January bug. Here's another way, addressing that problem in a slightly different way from yours (less work :-) irb(main):035:0> d = Date.today << 1 => # irb(main):036:0> Date.new(d.year, d.month, 1).to_s => "2005-07-01" January test: irb(main):037:0> d = Date.new(2005,1,15) << 1 => # irb(main):038:0> Date.new(d.year, d.month, 1).to_s => "2004-12-01" David -- David A. Black dblack@wobblini.net