How to find a date that is three days earlier than a given date in Perl?

How to find a date that is 3 days earlier than a given date in Perl, where is the format YYYY-MM-DD?

+5
source share
7 answers

Date::Calc is the champion module here:

use strict;
use warnings;
use Date::Calc qw(Add_Delta_YMD);

my $startDate = '2000-01-01';
my ($startYear, $startMonth, $startDay) = $startDate =~ m/(\d{4}-(\d{2})-\d{2})/;

# 1 year, 2 months, 3 days, after startDate
my $endDate = join('-', Add_Delta_YMD($startYear, $startMonth, $startDay, 1, 2, 3));

The module has a huge number of time conversion procedures, especially those related to deltas. DateTimeand Date::Manipalso worth checking.

+10
source

Date :: Calc can be used for such calculations:

#!/usr/bin/perl

use strict;
use warnings;
use Date::Calc qw(Add_Delta_Days);

my ( $yyyy, $mm, $dd ) = ( 2009, 9, 2 );
my @date = Add_Delta_Days( $yyyy, $mm, $dd, -3 );
print join( '-', @date );
+9
source

DateTime - Perl:

use DateTime;

my ($year, $month, $day) = split '-', '2009-09-01';

my $date = DateTime->new( year => $year, month => $month, day => $day );

$date->subtract( days => 3 );

# $date is now three days earlier (2009-08-29T00:00:00)
+6

, . , , - .

() . Date::Calc Date::Manip - , DateTime .

+4

. perldoc POSIX mktime().

, Unix ( 1 1970 , ). 3 () 24 ( ) 60 ( ) 60 ( ) 259200 localtime(), .

, , *, . , , , , .


EDIT: * CPAN.

+1

The optimal thing about mktimeis that it will handle any time offset. It uses January = 0; and Year 2009 = 109 in this pattern. Thus, the print month is 1 and the full year is 1900.

use POSIX qw<mktime>;

my ( $year, $month, $day ) = split '-', $date;
my $three_day_prior = mktime( 0, 0, 0, $day - 3, $month - 1, $year - 1900 );

mktimeuseful for finding the last day of the month. You just go the next day the next day.

mktime( 0, 0, 0, 0, $month, $year - 1900 );
0
source

It's just with Date::Simple

C:\>perl -MDate::Simple=today -e "print today()-3"
2009-08-30
0
source

All Articles