在Perl中如何找到给定日期的上一个星期一的日期? [英] In Perl how to find the date of the previous Monday for a given date?
问题描述
我正在寻找一个Perl脚本,可以在任何指定的日期给我上个星期一。
I am looking for a Perl script which can give me the last Monday for any specified date.
对于日期2011-06-11,脚本应该返回2011-06-06
e.g. For date 2011-06-11, the script should return 2011-06-06
推荐答案
我假设如果给定日期是星期一,你想要同一个日期(而不是前一个星期一)。以下是 DateTime 的一种方法:
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";
(实际上,对于星期一的特殊情况,%7
不是必需的,因为
$ date-> day_of_week - 1
将始终为0– 6,而mod 7是一个无效使用%7
,它适用于任何所需的星期几,而不仅仅是星期一。)
(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);
如果您需要解析在命令行输入的日期,您可能需要查看 DateTime :: Format :: Natural 。
If you need to parse a date entered on the command line, you might want to look at DateTime::Format::Natural.
这篇关于在Perl中如何找到给定日期的上一个星期一的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!