我有以下循環來計算當前周的日期並將其打印出來。它的工作原理,但我在Perl中游泳的日期/時間的可能性,並希望得到你的意見是否有更好的方法。下面是我寫的代碼:如何在Perl中獲取本週的日期?
#!/usr/bin/env perl
use warnings;
use strict;
use DateTime;
# Calculate numeric value of today and the
# target day (Monday = 1, Sunday = 7); the
# target, in this case, is Monday, since that's
# when I want the week to start
my $today_dt = DateTime->now;
my $today = $today_dt->day_of_week;
my $target = 1;
# Create DateTime copies to act as the "bookends"
# for the date range
my ($start, $end) = ($today_dt->clone(), $today_dt->clone());
if ($today == $target)
{
# If today is the target, "start" is already set;
# we simply need to set the end date
$end->add(days => 6);
}
else
{
# Otherwise, we calculate the Monday preceeding today
# and the Sunday following today
my $delta = ($target - $today + 7) % 7;
$start->add(days => $delta - 7);
$end->add(days => $delta - 1);
}
# I clone the DateTime object again because, for some reason,
# I'm wary of using $start directly...
my $cur_date = $start->clone();
while ($cur_date <= $end)
{
my $date_ymd = $cur_date->ymd;
print "$date_ymd\n";
$cur_date->add(days => 1);
}
如前所述,這個工作,但它是最快捷,最有效的?我猜測速度和效率可能不一定會一起,但您的反饋非常感謝。
感謝您的更新代碼。 – ABach 2010-05-26 21:45:57
一個簡單的問題 - 是否爲循環創建一個新的日期時間克隆每次迭代?這在Perl中可以嗎? – ABach 2010-05-26 21:56:32
請注意,星期日版本無法正常工作。你需要在' - > truncate'之前加'(> = 1)',或者從星期天開始給你開始前一週。 – cjm 2010-05-26 22:24:49