From: 7stud -- Date: 2011-05-01T04:41:43+09:00 Subject: Re: question about working with dates eggman2001 wrote in post #995956: > I have a list (in database) of weekday non-holiday dates that goes > from present back to 1990. From this list, I'd like to pull out dates > given different kinds of criteria and add them to an array. Examples > of criteria are: > - first day of the month for the most recent 5 years. Perhaps obvious, > but the first weekday non-holiday of the month isn't necessarily day 1 > (i.e. 5/1). > All it takes is a little math: require 'date' #Create array of all weekday dates for last five years #(probably faster than pulling them out of a database): date_arr = [] previous_years = 5 1.upto(previous_years * 365) do |i| new_date = today - i next if [6,0].include?(new_date.wday) date_arr << new_date end #Print out the first weekday of each month: date_arr.each do |date| year = date.year month = date.month first_day_of_month = Date.new(year, month, 1) while [6,0].include?(first_day_of_month.wday) first_day_of_month += 1 end if date == first_day_of_month puts date end end --output:-- 2011-04-01 2011-03-01 2011-02-01 2011-01-03 2010-12-01 2010-11-01 2010-10-01 2010-09-01 2010-08-02 2010-07-01 2010-06-01 2010-05-03 2010-04-01 2010-03-01 2010-02-01 2010-01-01 2009-12-01 2009-11-02 2009-10-01 2009-09-01 2009-08-03 2009-07-01 2009-06-01 2009-05-01 2009-04-01 2009-03-02 2009-02-02 2009-01-01 2008-12-01 2008-11-03 2008-10-01 2008-09-01 2008-08-01 2008-07-01 2008-06-02 2008-05-01 2008-04-01 2008-03-03 2008-02-01 2008-01-01 2007-12-03 2007-11-01 2007-10-01 2007-09-03 2007-08-01 2007-07-02 2007-06-01 2007-05-01 2007-04-02 2007-03-01 2007-02-01 2007-01-01 2006-12-01 2006-11-01 2006-10-02 2006-09-01 2006-08-01 2006-07-03 2006-06-01 2006-05-01 -- Posted via http://www.ruby-forum.com/.