How do months go by in Perl based on different days in a month?

I was wondering if there is a built-in Perl function that adjusts the date if you take a month for it. For instance. if the date is the 31st, it will be adjusted until the end of the previous month, if it does not have 31 days.

I would just change it to the 30th easily, if not for the months with 31 days next to each other (December / January, July / August) and February. I just want to save the date for a certain amount of time from the current date, for example.

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);

$current_date = join("-", (1900+$year), ($mon+1), $mday);
$one_month_ago = join("-", (1900+$year), ($mon), $mday);
$one_year_ago = join("-", (1899+$year), ($mon+1), $mday);

I can deal with the February copy, since it applies only to years, but if it was adopted on December 31, 2012, then the month will be taken away on November 31, 2012, which, of course, does not exist. I thought I would ask if there is a function before complicating things for myself ... thanks :)

+5
3

DateTime, , .

localtime POSIX::mktime:

use POSIX qw( mktime );

my @t = localtime $epoch;
$t[4] -= 2;  # $t[4] is tm_mon
my $two_months_ago = mktime @t;

mktime() ; , Janurary 2 - .. // .

+8

DateTime , , :

#!/usr/bin/perl
use strict;
use warnings;

use feature qw( say );
use DateTime;

my $dt = DateTime->now;
say $dt->ymd;

$dt->truncate( to => month );

say $dt->ymd;

$dt->add( days => -1 );
say $dt->ymd;

foreach ( 1 .. 12 ) { 
    $dt->add( months => -1 );
    say $dt->ymd;
} 

(29 2012 .), :

[~] $ perl dt.pl 
2012-08-29
2012-08-01
2012-07-31
2012-06-30
2012-05-31
2012-04-30
2012-03-31
2012-02-29
2012-01-31
2011-12-31
2011-11-30
2011-10-31
2011-09-30
2011-08-31
2011-07-31
+10

DateTime. , .

use strict;
use DateTime;

my $epoch = ...;
my $dt    = DateTime->from_epoch( epoch => $epoch );
$dt->subract(months => 1);

printf "%s", $dt->datetime();
+7

All Articles