gpt4 book ai didi

Perl DateTime 模块计算第一、第二、第三、第四、最后一个星期日、星期一、...每个月的星期六

转载 作者:行者123 更新时间:2023-12-02 08:38:27 29 4
gpt4 key购买 nike

我正在使用 Perl DateTime Module ,我想知道如何计算 FirstSecondThirdFourth最后 星期日星期一,...指定月份的星期六

我的方法:

从 i= 1...DateTime->last_day_of_month( ... ) 开始循环。

将日期 i 分配给 date($dt) 并使用 $dt->day_of_week() 获取星期几。

使用计数器跟踪第一、第二、第三、第四、最后。

如果星期几与所需的日期匹配并且计数器与所需的时间间隔匹配,则中断循环。

您能否提出比上述更好(或更短)的方法?感谢任何帮助。

最佳答案

这是对 my answer for finding the previous Monday (or any specified day of the week) 的直接修改.唯一的困难是弄清楚您的开始日期。

use DateTime;

# Here $nth is 1, 2, 3... for first, second, third, etc.
# Or -1, -2, -3... for last, next-to-last, etc.
# $dow is 1-7 for Monday-Sunday
# $month is 1-12
sub nth_day_of_month {
my ($nth, $dow, $year, $month) = @_;

my $date = ($nth > 0
# For 1st etc. we want the last day of that week
# (i.e. 7, 14, 21, 28 ...). We have to use add because
# the last week may extend into next month.
? DateTime->new(year => $year, month => $month, day => 1)
->add( days => $nth * 7 - 1)
# For last etc. we want the last day of the month
# (minus a week if next-to-last, etc)
: DateTime->last_day_of_month(year => $year, month => $month)
->add( weeks => $nth + 1)); # $nth is negative

# Back up to the first $dow on or before $date
$date->subtract(days => ($date->day_of_week - $dow) % 7);

# If we're not in the right month, then that month doesn't have the
# specified date (e.g. there's no 5th Tuesday in Sept. 2013).
return (($date->month == $month) ? $date : undef);
}

更新:这是一个稍微更高效的版本。它使用相同的算法,但它结合了对 addsubtract 的调用,因此它只需执行一次日期数学运算。

sub nth_day_of_month {
my ($nth, $dow, $year, $month) = @_;

my ($date, $delta);
if ($nth > 0) {
# For 1st etc. we want the last day of that week (i.e. 7, 14, 21, 28, "35")
$date = DateTime->new(year => $year, month => $month, day => 1);
$delta = $nth * 7 - 1;
} else {
# For last etc. we want the last day of the month
# (minus a week if next-to-last, etc)
$date = DateTime->last_day_of_month(year => $year, month => $month);
$delta = 7 * ($nth + 1); # $nth is negative
}

# Back up to the first $dow on or before $date + $delta
$date->add(days => $delta - ($date->day_of_week + $delta - $dow) % 7);

# If we're not in the right month, then that month doesn't have the
# specified date (e.g. there's no 5th Tuesday in Sept. 2013).
return (($date->month == $month) ? $date : undef);
}

关于Perl DateTime 模块计算第一、第二、第三、第四、最后一个星期日、星期一、...每个月的星期六,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18908238/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com