Get an array of months in Perl

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.

You’ll need Date::Manip::Recur

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 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();

# 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/;
  print parseMonth($curMonth)
}

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));
}

comments powered by Disqus