我使用以下循环来计算当前周的日期并将其打印出来。它是有效的,但是我正在处理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 );
}正如前面提到的,这是可行的,但它是最快的还是最有效的?我猜速度和效率可能不一定会结合在一起,但您的反馈非常感谢。
发布于 2010-05-27 05:16:08
对friedo的回答稍加改进的版本...
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那样重新实现它;)
发布于 2010-05-27 04:33:56
可以使用DateTime对象以数字( 1-7 )的形式获取一周中的当前日期。然后只需使用它来查找当前周的星期一。例如:
my $today = DateTime->now;
my $start = $today->clone;
# move $start to Monday
$start->subtract( days => ( $today->wday - 1 ) ); # Monday gives 1, so on monday we
# subtract zero.
my $end = $start->clone->add( days => 7 );以上这些都是未经测试的,但是这个想法应该是可行的。
发布于 2010-05-27 21:54:07
这样行得通吗:
use strict;
use warnings;
use POSIX qw<strftime>;
my ( $day, $pmon, $pyear, $wday ) = ( localtime )[3..6];
$day -= $wday - 1; # Get monday
for my $d ( map { $day + $_ } 0..6 ) {
print strftime( '%A, %B %d, %Y', ( 0 ) x 3, $d, $pmon, $pyear ), "\n";
}我只是把它们打印出来作为说明。您可以将它们存储为时间戳,如下所示:
use POSIX qw<mktime>;
my @week = map { mktime(( 0 ) x 3, $day + $_, $pmon, $pyear ) } 0..6;https://stackoverflow.com/questions/2916522
复制相似问题