Search code examples
perldatetimetimezonenls

PERL : I take mday value from locatime as below , . How can I subtract 1 from mday which I take from localtime


PERL : I take mday value from locatime as below ,now I want value of day before yesterday . How can I subtract 1 from mday which I take from localtime

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
my $part = "P".$mday;

print "Today value is $part \n";

my $part_yes = "P".$mday - $num;

print "$part_yes \n";

Solution

  • Using DateTime:

    my $dt =
       DateTime
       ->now( time_zone => 'local' )
       ->set_time_zone('floating')  # Do this when working with dates.
       ->truncate( to => 'days' );  # Optional.
    
    $dt->subtract( days => 2 );
    
    my $yesterday = $dt->day;
    

    DateTime is pretty heavy, and it seems people asking date-time questions invariably come back and say "core modules only!", so here's a solution using only core modules.

    use Time::Local qw( timegm );
    
    # Create an timestamp with the same date in UTC as the one local one.
    my $epoch = timegm(0, 0, 0, ( localtime() )[3,4,5]);
    
    # We can now do date arithmetic without having to worry about DST switches.
    $epoch -= 2 * 24*60*60;
    
    my $yesterday = ( gmtime($epoch) )[3] + 1;