Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find a date which is three days earlier than a given date in Perl?

Tags:

date

perl

How do I find a date which is 3 days earlier than a given date in Perl where the format is YYYY-MM-DD?

like image 978
biznez Avatar asked Sep 02 '09 05:09

biznez


4 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 routines, particularly those dealing with deltas. DateTime and Date::Manip are also worth checking out.

like image 176
Ether Avatar answered Nov 18 '22 00:11

Ether


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 );
like image 31
Alan Haggai Alavi Avatar answered Nov 17 '22 22:11

Alan Haggai Alavi


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)
like image 40
draegtun Avatar answered Nov 17 '22 23:11

draegtun


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.

like image 4
Jonathan Leffler Avatar answered Nov 18 '22 00:11

Jonathan Leffler