Search for Perl 5.12 code that generates yesterday's date in DDMMYY format

I would like to get an easy way to get yesterday (local time) as a string in a Perl script. Preferably, I would like to do this without any dependencies between the modules, since we have installed a boneless Perl 5.12 installation.

So something like:

my $yesterdays_date=...; # Puts for example '301011' into $yesterdays_date, # if today is October 31st, 2011 
+4
source share
4 answers

Time::Piece is the main:

 use Time::Piece; use Time::Seconds qw(ONE_DAY); my $yesterday = localtime() - ONE_DAY(); print $yesterday->strftime('%d%m%y'), "\n"; 

If you are concerned about daylight saving time, you can normalize the current time until noon:

 use Time::Piece; use Time::Seconds qw(ONE_DAY ONE_HOUR); my $today = localtime; my $yesterday = $today + ONE_HOUR * ( 12 - $today->hour ) - ONE_DAY; print $yesterday->strftime("%d%m%y"), "\n"; 

If you can live with dependencies, use DateTime :

 use DateTime; print DateTime->now->subtract(days => 1)->strftime('%d%m%y'), "\n"; 
+12
source

If you want to go with dependencies, DateTime will usually do whatever you need.

 use strict; use warnings; use 5.012; use DateTime; say DateTime->now->subtract(days => 1)->strftime('%d%m%y'); 
+13
source

You can use the POSIX module as follows:

 perl -MPOSIX=strftime -le 'print strftime "%m%d%y",localtime(time-(60*60*24))' 
+1
source

Just subtract 24 hours (24 hours * 60 minutes * 60 seconds) from the current time and get the local time:

 say scalar localtime(time - 60*60*24); # Sun Oct 30 21:04:30 2011 

Note that localtime returns time in string format only in a scalar context. If you need to create "DDMMYY", you can simply use the data structure returned by the list context:

 my @tm = localtime(time - 60*60*24); my $date = sprintf("%02d%02d%2d", $tm[3], $tm[4]+1, $tm[5] + 1900); # 30102011 
0
source

Source: https://habr.com/ru/post/1379011/


All Articles