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

后端 未结 9 995
深忆病人
深忆病人 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:25

    If you are a slave like me and have to use a corporate Perl without libraries and you are not allowed to install them either, old fashioned way:

    my $datestring = "";
    my $secondsEpoc = time(); #gives the seconds from system epoch
    my $secondsWantedDate;
    my $seconds2substract;
    
    $datestring = localtime($secondsEpoc);
    print "Today's date and time ".$datestring."\n";
    my ($second,$minute,$hour,$d,$M,$y,$wd,$yd) = (localtime)[0,1,2,3,4,5,6,7];
    #print "hour: ".$hour;
    #print "minute: ".$minute;
    #print "second: ".$second;
    #print "week day: ".$wd; #week day is 1=Monday .. 7=Sunday
    
    $seconds2substract = 24 * 60 * 60;  # seconds in 24 hours
    $secondsWantedDate=$secondsEpoc-$seconds2substract;
    $datestring = localtime($secondsWantedDate);
    print "Yesterday at the same time ".$datestring."\n";
    
    
    my $days2Substract = $wd-1;
    $seconds2substract = ($days2Substract * 24 * 60 * 60);
    $secondsWantedDate=$secondsEpoc-$seconds2substract;
    $datestring = localtime($secondsWantedDate);
    print "Past Monday same time ".$datestring."\n";
    
    $seconds2substract = ($days2Substract * 24 * 60 * 60) + ($hour *60 *60) + ($minute * 60) + $second;
    $secondsWantedDate = $secondsEpoc-$seconds2substract;
    $datestring = localtime($secondsWantedDate);
    print "Past Monday at 00:00:00  ".$datestring."\n";
    

    Hope it helps somebody!

    0 讨论(0)
  • 2020-12-11 04:29

    Zeller's congruence will give you the day of the week. From there it should be pretty easy.

    0 讨论(0)
  • 2020-12-11 04:31

    You could use Date::Manip, which has a Date_GetPrev function and understands "Monday"

    $ perl -MDate::Manip -le 'print UnixDate(Date_GetPrev(shift, "Monday", 0), "%Y-%m-%d")' 2011-06-11
    2011-06-06
    
    0 讨论(0)
提交回复
热议问题