use strict;
use warnings;

use Time::Local;
#use POSIX qw/strftime/;
use POSIX;

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time());

{
        my $date1 = timelocal(0,0,12,$mday,$mon,$year);
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($date1);
        my $date1_2 = sprintf("%4d-%02d-%02d %02d:%02d:%02d\n", $year+1900, $mday+1, $mon, $hour, $min, $sec);
        print ("Mid Today:\n", $date1, "\t", $date1_2, "\n");
}

{
        my $delta_days = -7;
        my $date2 = timelocal(0,0,12,$mday,$mon,$year) + $delta_days*86400;
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($date2);
        my $date2_2 = sprintf("%4d-%02d-%02d %02d:%02d:%02d\n", $year+1900, $mday+1, $mon, $hour, $min, $sec);
        print ("Delta ", $delta_days, " days:\n", $date2, "\t", $date2_2);
}

“As tempting as it is to just subtract a day’s worth of seconds from the current time, there are times when this will yield the wrong answer (leap seconds, DST, and possibly others). I find it easier to just let strftime (available in the Perl 5 core module POSIX) take care of all of that for me.”

#!/usr/bin/perl

use strict;
use warnings;

use Time::Local;
use POSIX qw/strftime/;

#2010-03-15 02:00:00
my ($s, $min, $h, $d, $m, $y) = (0, 0, 0, 15, 2, 110);

my $time = timelocal $s, $min, $h, $d, $m, $y;
my $today = strftime "%Y-%m-%d %T", localtime $time;
my $yesterday = strftime "%Y-%m-%d %T", $s, $min, $h, $d - 1, $m, $y;
my $oops = strftime "%Y-%m-%d %T", localtime $time - 24*60*60;
print "$today -> $yesterday -> $oops\n";


I had problems with negative variables when I used this method. Apparently this wouldn’t be a problem if I was using Perl5: “It may not be standard in POSIX (or SUS), but it is standard in Perl 5. The documentation says arguments are made consistent as though by calling "mktime()" before calling your system's "strftime()""

Advertisements