计算下一个星期一到给定日期的日期

时间:2012-05-01 06:42:56

标签: perl datetime

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

在另一篇文章中,我发现了一个脚本,使用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)

我根本无法找到如何修改这个以便计算下一个星期一(而不是前一个星期一)。 有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

更改

$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); 

答案 1 :(得分: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");

答案 2 :(得分: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 );