Search code examples
perllocaltime

How do I get yesterday's date using localtime?


How do I tweak this to get yesterday's date using localtime?

use strict;

sub spGetCurrentDateTime;
print spGetCurrentDateTime;

sub spGetCurrentDateTime {
my ($sec, $min, $hour, $mday, $mon, $year) = localtime();
my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
my $currentDateTime = sprintf "%s %02d %4d", $abbr[$mon], $mday, $year+1900; #Returns => 'Aug 17 2010' 
return $currentDateTime;
}

~


Solution

  • The DST problem can be worked around by taking 3600s from midday today instead of the current time:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use Time::Local;
    
    sub spGetYesterdaysDate;
    print spGetYesterdaysDate;
    
    sub spGetYesterdaysDate {
    my ($sec, $min, $hour, $mday, $mon, $year) = localtime();
    my $yesterday_midday=timelocal(0,0,12,$mday,$mon,$year) - 24*60*60;
    ($sec, $min, $hour, $mday, $mon, $year) = localtime($yesterday_midday);
    my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
    my $YesterdaysDate = sprintf "%s %02d %4d", $abbr[$mon], $mday, $year+1900;
    return $YesterdaysDate;
    }
    

    In light of the "unspecified" documented behaviour of the strftime solution suggested by Chas, this approach might be better if you're not able to test for expected-but-not-guaranteed results across multiple platforms.