0

我有一系列日期——比如 2012-01-30 .. 2012-04-06——表示这些日期内的一组周。这些周编号为 1 到 10。给定今天的日期(例如,2012-02-29),我希望能够获得该范围内的周数(在本例中为 5)。我如何在 Perl 中实现这一点?

4

3 回答 3

3

Time::Piece具有strptime将字符串解析为时间对象的week方法和指示时间对象的星期数的方法。

use Time::Piece;
my @dates = ('2012-01-30', ..., ...., '2012-04-06');

foreach my $strdate (@dates) {
    my $date = Time::Piece->strptime($strdate, "%Y-%m-%d");
    print "Number of week for '$strdate' is " . $date->week . "\n";
}

您需要做的只是计算您范围内的独特周数。

于 2012-01-28T12:31:18.410 回答
1

除非您想结合一些值检查,否则结束日期的值没有任何区别。您需要的值是week(start date) - week(this date) + 1。我推荐该Date::Calc模块的整洁和高效。代码看起来像这样

use strict;
use warnings;

use Date::Calc 'Week_Number';

sub week {
  Week_Number(split /-/, $_[0]);
}

print week('2012-02-29') - week('2012-01-30') + 1, "\n";

输出

5
于 2012-01-28T13:48:56.137 回答
1
use DateTime qw();
my (undef, $initial_weeknumber) 
    = DateTime->new(year => 2012, month => 1, day => 30)->week;
my (undef, $target_weeknumber)  
    = DateTime->new(year => 2012, month => 2, day => 29)->week;
printf 'We are in week %d of the Jashank epoch.', 
    1 + $target_weeknumber - $initial_weeknumber;
于 2012-01-28T19:15:15.570 回答