Search code examples
perldate

How do I get yesterday's date in 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"`;

Solution

  • If you want yesterday's date:

    use DateTime qw( );
    
    my $yday_date =
       DateTime
          ->now( time_zone => 'local' )
          ->set_time_zone('floating')
          ->truncate( to => 'day' )
          ->subtract( days => 1 )
          ->strftime('%Y-%m-%d');
    

    For example, in New York on 2019-05-14 at 01:00:00, it would have returned 2019-05-13.

    For example, in New York on 2019-11-04 at 00:00:00, it would have returned 2019-11-03.

    Note that ->now( time_zone => 'local' )->set_time_zone('floating')->truncate( to => 'day' ) is used instead of ->today( time_zone => 'local' ) to avoid this problem.


    If you want the time a day earlier:

    use DateTime qw( );
    
    my $yday_datetime =
       DateTime
          ->now( time_zone => 'local' )
          ->subtract( days => 1 )
          ->strftime('%Y-%m-%d %H:%M:%S');
    

    For example, in New York on 2019-05-14 at 01:00:00, it would have returned 2019-05-13 01:00:00.

    For example, in New York on 2019-03-10 at 12:00:00, it would have returned 2019-03-09 12:00:00.

    For example, in New York on 2019-03-11 at 02:30:00, it would have resulted in an error. 2019-03-10 02:30:00 didn't exist because of the switch to Daylight Saving Time.


    If you want the time 24 hours earlier:

    use DateTime qw( );
    
    my $yday_datetime =
       DateTime
          ->now( time_zone => 'local' )
          ->subtract( hours => 24 )
          ->strftime('%Y-%m-%d %H:%M:%S');
    

    For example, in New York on 2019-05-14 at 01:00:00, it would have returned 2019-05-13 01:00:00.

    For example, in New York on 2019-03-10 at 12:00:00, it would have returned 2019-03-09 11:00:00.

    For example, in New York on 2019-03-11 at 02:30:00, it would have returned 2019-03-10 01:30:00.