Get an array of months in perl

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 HTML::Mason, but you get the idea.

You’ll need Date::Manip::Recur

<select name="months" id="months">
% # Loop through the date objects
% for (@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/;
      <option value="<% $curMonth %>"><% parseMonth($curMonth) %></option>
% }

# Returns a date like "2011-01-01"
my $monStart = getOldestEntry($account);

use Date::Manip::Recur;
  my $recur = new Date::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 dates
  my @dates = $recur->dates();

sub parseMonth {
use Time::Local;
use Date::Format;
  my $md = shift;

  # Match on YYYYMM
  $date =~ m/^(\d{4})(\d{2})/;
  my $year = $1; my $mon = $2;

  # Convert to epoch
  my $time = timelocal(0,0,0,1,$mon-1,$year);

# Return back (%B %Y) as "August 2010"
return(time2str("%B %Y", $time));

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.