perl - 我如何在Perl中获得本周的日期?

标签 perl datetime

我有以下循环来计算当前星期的日期并打印出来。它可以工作,但是我在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 );
}

如前所述,这可行,但是最快还是最有效?我猜想速度和效率可能不一定会结合在一起,但您的反馈意见值得我们赞赏。

最佳答案

弗里多的答案的略有改进的版本...

my $start_of_week =
    DateTime->today()
            ->truncate( to => 'week' );

for ( 0..6 ) {
    print $start_of_week->clone()->add( days => $_ );
}

但是,这假设星期一是一周的第一天。对于星期日,从...开始
my $start_of_week =
    DateTime->today()
            ->truncate( to => 'week' )
            ->subtract( days => 1 );

无论哪种方式,最好使用truncate方法而不是像Friedo那样重新实现它;)

关于perl - 我如何在Perl中获得本周的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2916522/

相关文章:

c# - 如何检查日期格式是否正确,即 yyyy-mmm-dd?

php - Mysql 查询日期 >= 90 天

javascript - 如何使用 JSON.NET 通过 ASP.NET MVC 传递 JSON 日期值?

arrays - 在 Perl 中使用 FTP 流中的哈希值

nhibernate - 在 NHibernate QueryOver 语法中使用 current_timestamp

python - 将带有日期时间索引的行插入数据框

linux - 当我尝试在 Linux 上将 DBD::Advantage 与 64 位 perl 一起使用时,为什么会得到 "Error 6060"?

perl - 为什么在文件范围内用 "my"声明 Perl 变量?

正则表达式在 Perl 中不匹配,而在其他程序中匹配

perl - 为什么这个 postgres 存储过程想要 `use utf8` ?