anilmwr anilmwr - 2 months ago 8
Perl Question

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

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

cjm cjm
Answer

I'm assuming that if the given date is a Monday, you want the same date (and not the previous Monday). Here's one way to do it with DateTime:

use DateTime;

my $date = DateTime->new(year => 2011, month => 6, day => 11);
my $desired_dow = 1;            # Monday
$date->subtract(days => ($date->day_of_week - $desired_dow) % 7);
print "$date\n";

(Actually, for the special case of Monday, the % 7 isn't necessary, because $date->day_of_week - 1 will always be 0–6, and that mod 7 is a no-op. But with the % 7, it works for any desired day-of-week, not just Monday.)

If you did want the previous Monday, you can change the subtraction:

$date->subtract(days => ($date->day_of_week - $desired_dow) % 7 || 7);

If you need to parse a date entered on the command line, you might want to look at DateTime::Format::Natural.