pauler
pauler

Reputation: 117

How to find the previous date in perl for a given date

How to find the previous date for a given date as Aug 17 in perl. I am able to get the current date in perl by using the below code. Can some-one help me to find the previous date for a given date.

Given date as : Aug 17
Required Date as : Aug 16
#Reverting the Date for the respective TimeZone
my $timezone='london';
my ($dt, $Curr_Bus_Date,$Curr_day);
$dt = DateTime->now(time_zone => $timezone);
$Curr_mon=$dt->strftime('%b');
$Curr_date=$dt->strftime('%d');
$Curr_date=~s/^0/ /;
$Curr_dt="$Curr_mon $Curr_date ";
print "The curr date is $Curr_dt \n";

Upvotes: 1

Views: 2555

Answers (3)

Dave Cross
Dave Cross

Reputation: 69274

The DateTime class has a subtract() method. It's clearly documented.

$ perl -MDateTime -E'say DateTime->now->subtract(days => 1)'
2012-08-16T10:31:25

You can also do it with Perl's standard (since 5.10) Time::Piece and Time::Seconds classes.

$ perl -MTime::Piece -MTime::Seconds -E'$t = localtime; $t -= ONE_DAY; say $t'Thu Aug 16 11:37:37 2012

With both of those approaches you should bear in mind that subtracting one day from the current date won't always get you to the previous day.

Upvotes: 5

Brian Agnew
Brian Agnew

Reputation: 272307

Have you considered Date::Manip and its date calculation facilities ?

I'd really check out CPAN for such commonly required functions. There's a lot of mature powerful modules there.

Upvotes: 0

Y__
Y__

Reputation: 1777

You can use the Add_Delta_Days method :

use Date::Calc qw(Add_Delta_Days);
($year, $month, $day) = Add_Delta_Days(2012,8,17,-1);

Regards,

Upvotes: 0

Related Questions