1

我希望返回给定日期的下周一的日期。如果给定日期已经是星期一,则日期应保持不变。

从另一篇文章中,我找到了一个脚本来使用 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";

(归功于 cjm)

我根本不知道如何修改它以计算下一个星期一(而不是前一个星期一)。有人可以帮忙吗?

4

3 回答 3

3

改变

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

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

或者您可以选择在“旧”星期一增加一周:

$date->subtract(days => ($date->day_of_week - $desired_dow) % 7); 
$date->add(days => 7); 
于 2012-05-01T06:46:08.397 回答
0
#!/usr/bin/perl

use strict;
use warnings;

use Time::Local;
use POSIX 'strftime';

my $date = shift || die "No date given\n\n\tUsage: ./test.pl 2017-07-17, please note the format, CCYY-MM-DD\n\n";

my @date = split /-/, $date;
$date[0] -= 1900;
$date[1]--;

die "Invalid date: $date\n" unless @date == 3;

my $now = &timelocal(0, 0, 12, reverse @date);

do{
    $now += 24 * 60 * 60;
#}while ((strftime('%u', localtime $now) != 1) && (strftime('%u', localtime $now) != 5) && (strftime('%u', localtime $now) != 3));  ## For Multiple days, in case you want to find either, next monday, friday or wednesday
}while (&strftime('%u', localtime $now) != 1);      #Values should be from 1 to 7, including...

my @array_of_time     = localtime($now);
my $formatted_time     = &strftime( "%Y%m%d", @array_of_time );
print ("Next Monday-[$formatted_time]\n");
于 2017-07-17T10:14:16.587 回答
0

在我看来,接受的答案(add部分)是不正确的。

这就是我使用的:

my $date = DateTime->now;
my $current_dow = $date->day_of_week;
my $desired_dow = 1; # Monday
$date->add( days => 7 - $current_dow + $desired_dow );
于 2018-01-06T21:17:04.870 回答