In Perl how to find the date of the previous Monday for a given date?

后端 未结 9 1052
深忆病人
深忆病人 2020-12-11 03:48

I am looking for a Perl script which can give me the last Monday for any specified date.

e.g. For date 2011-06-11, the script should return 2011-06-06

9条回答
  •  难免孤独
    2020-12-11 04:21

    There are lot of ways to do it in Perl. Here is how it can be done with Perl library Moment.

    #!/usr/bin/perl
    
    use strict;
    use warnings FATAL => 'all';
    use feature 'say';
    
    use Moment;
    
    sub get_monday_date {
        my ($date) = @_;
    
        my $moment = Moment->new( dt => "$date 00:00:00" );
    
        my $weekday_number = $moment->get_weekday_number( first_day => 'monday' );
    
        my $monday = $moment->minus( day => ($weekday_number - 1) );
    
        return $monday->get_d();
    }
    
    say get_monday_date('2011-06-11'); # 2011-06-06
    

提交回复
热议问题