One note... if you have a daylight savings time that takes effect between 11pm and 1am this won't work. In the US DST is 2am, so it is safe.
Also, this might be a prettier solution...
use Time::Local; use constant DAY => 86_400;
$current = time; $previous = subtract_month(time, 1); $current_2 = subtract_month(time, 2);
print get_date($current), "\n"; print get_date($previous), "\n"; print get_date($current_2), "\n";
sub subtract_month { my $time = shift; my $months = shift;
if ($months) { $time = subtract_month(first_day($time) - DAY, --$months) }
return $time; }
sub first_day { my $time = shift; my @time = localtime($time); $time[3] = 1; return timelocal(@time); }
sub get_date { my $time = shift; my @time = localtime($time); return sprintf('%02d-%04d', $time[4]+1, $time[5]+1900); }
I played with a different approach, without Time::Local (and not affected by DST):
my %m; @{ $m{curr} } = (localtime)[4,5]; $m{curr}[0] ++; $m{curr}[1] += 1900;
sub back { if ($_[0] - 1) { $_[0] - 1, $_[1] } else { 12, $_[1] - 1 } }
@{ $m{prev} } = back @{ $m{curr} }; @{ $m{curr_2} } = back @{ $m{prev} };
my %months = map { $_, sprintf '%02d-%d', @{ $m{$_} } } qw/curr prev curr_2/;
print "\$months{$_}: $months{$_}\n" for qw/curr prev curr_2/;
Outputs: $months{curr}: 09-2004 $months{prev}: 08-2004 $months{curr_2}: 07-2004
-- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>