Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get yesterday's date in perl?

Tags:

date

perl

Currently i take today date using below.I need to get yesterday date using this.. how can i get that ?

my $today = `date "+%Y-%m-%d"`;
like image 611
Debugger Avatar asked May 14 '19 02:05

Debugger


1 Answers

I recommend using DateTime (as described in ikegami's answer). But if you don't want to install a CPAN module, this method uses only features available in the standard Perl installation.

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Time::Local;
use POSIX 'strftime';

# Get the current date/time
my ($sec, $min, $hr, $day, $mon, $yr) = localtime;

# Get the epoch seconds for midday today
# (we use midday to eliminate potential problems
# when entering or leaving daylight savings time)
my $midday = timelocal(0, 0, 12, $day, $mon, $yr);

# Subtract a day's worth of seconds from the epoch
my $midday_yesterday = $midday - (24 * 60 * 60);

# Convert that epoch value to a string date using
# localtime() and POSIX::strftime().
my $yesterday = strftime('%Y%m%d', localtime($midday_yesterday));

say $yesterday;
like image 110
Dave Cross Avatar answered Oct 23 '22 17:10

Dave Cross