How do I find a date which is 3 days earlier than a given date in Perl where the format is YYYY-MM-DD?
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 routines, particularly those dealing with deltas. DateTime
and Date::Manip
are also worth checking out.
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 );
DateTime is the canonical way for dealing with dates in modern 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)
There are so many options that it is moderately embarrassing. It depends in part on what other calculations you might need in the future, and whether times and time zones will ever be a factor, and similar things.
You could look at any of these
Date::Calc
Date::Manip
DateTime::*
- see also datetime.perl.org (though that site did not seem to be responding on 2009-09-01T22:30-07:00)to name but three (sets of) modules. I'd suggest Date::Calc
or Date::Manip
for simplicity - but if you're going to need to get fancy in future, the DateTime
modules may be better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With