my $one_month_ago = DateTime
->now( time_zone => 'local' )
->subtract( days => 30 );
I agree that DateTime is a good choice, but note that "one month ago" is not the same as "30 days ago", and date math works the same as DateTime in this case:
use DateTime;
my $dt = DateTime->new(year=>2017,month=>3,day=>1);
print $dt->ymd, "\n";
print "-30 days: ",
$dt->clone->subtract(days=>30)->ymd, " ";
system('date','+%Y-%m-%d','-d 2017-03-01 -30 days')==0 or die $?;
print "-1 month: ",
$dt->clone->subtract(months=>1)->ymd, " ";
system('date','+%Y-%m-%d','-d 2017-03-01 -1 month')==0 or die $?;
__END__
2017-03-01
-30 days: 2017-01-30 2017-01-30
-1 month: 2017-02-01 2017-02-01
For younggrasshopper13: If you want to get the past 24 months starting with the current, here's one way:
use DateTime;
my $dt = DateTime->now->truncate(to=>'month');
for (1..24) {
my $last = $dt->clone->add(months=>1)->subtract(days=>1);
print $dt->ymd," to ",$last->ymd,"\n";
$dt->subtract(months=>1);
}
__END__
2017-06-01 to 2017-06-30
2017-05-01 to 2017-05-31
2017-04-01 to 2017-04-30
... etc.
And just for the sake of TIMTOWTDI, another, although not exactly the same:
use DateTime;
my $now = DateTime->now;
for ( my $dt = $now->clone->truncate(to=>'month')
->subtract(years=>2)->add(months=>1);
$dt < $now;
$dt->add(months=>1) ) {
my $last = DateTime->last_day_of_month(year=>$dt->year,
month=>$dt->month,time_zone=>$dt->time_zone);
print $dt->ymd," to ",$last->ymd,"\n";
}
__END__
2015-07-01 to 2015-07-31
2015-08-01 to 2015-08-31
2015-09-01 to 2015-09-30
...
Note that DateTime->now defaults to using UTC, so if you want something else, specifying DateTime->now(time_zone=>...) like thanos1983 showed is not a bad idea. But keep in mind that time_zone=>'local' will make it depend on the current configuration of the local machine, so if you want consistency, consider using a specific time zone like time_zone=>'America/Chicago'.
Update: Changed the last example to use a for(;;) loop, just to add some variety. |