Posted by
Michael Palmer
on
Tuesday, October 4, 2011
I had a need to build an array of months between a set month and the current month. My purpose was to let the user choose a month to build a report for.
I’m using this on the web, so I’m printing out dates.
# Returns a date like "2011-01-01"my$monStart=getOldestEntry($account);useDate::Manip::Recur;my$recur=newDate::Manip::Recur;# Parse out the first of the month for every month since start until today.my$err=$recur->parse('0:0*0:0:0:0:0',$monStart,$monStart,"Today");# Return an array object of datesmy@dates=$recur->dates();# Loop through the date objectsfor(@dates){# Assign the current month value to a scalar.my$curMonth=$_->value();# I only cared to see YYYYMM so I regex'd it.$curMonth=~s/^(\d{4})(\d{2}).*$/$1$2/;printparseMonth($curMonth)}subparseMonth{useTime::Local;useDate::Format;my$md=shift;# Match on YYYYMM$date=~m/^(\d{4})(\d{2})/;my$year=$1;my$mon=$2;# Convert to epochmy$time=timelocal(0,0,0,1,$mon-1,$year);# Return back (%B %Y) as "August 2010"return(time2str("%B %Y",$time));}