From: "lrlebron@..." Date: 2007-01-23T07:05:11+09:00 Subject: Re: find monday of first week of the month You may want to try the chronic library require 'chronic' date_start = Chronic.parse("Monday of first week of February") Daniel Liebig wrote: > Hi, > > im pretty new to Ruby and i tried to find out how to calculate the date > for the first monday of the first week of the month (i.e. this would be > 2007-01-29 for Feb. 2007) > My approach is to get the weekday of the first day of the month and > calculate back from there. By getting the weekday i can tell how far to > calculate back (if necessary at all). If i'm calcualating back from > janurary, i also have to switch back the year. > > So this is what i came out with: > > year = 2007 > month = 2 > > # get the weekday of the first day of the month > first_wd = Date.new(year, month, 1).wday > > # if weekday is sunday > if first_wd == 0 > date_modifier = - 6 > > #if weekday is monday > elsif first_wd == 1 > date_modifier = 1 > > # any other day > else > date_modifier = - ( first_wd - 1 ) > end > > #if i have to count back, swith month (and year) back > if date_modifier < 0 > if month > 1 > month -= 1 > else > month = 12 > year -= 1 > end > end > > # get date with calculated modifier > date_start = Date.new(year, month, date_modifier ) > > Ok, this works, but it seems pretty complicated to me. Is there a > smarter (and more readable) way to do this? As far as i know Ruby right > now, it's pretty unusual if an "easy" problem like this needs more than > three lines of code ;). > > Thx for any help > Regards > Daniel