在Perl中查找日期范围内的周数

时间:2012-01-28 11:49:06

标签: perl date-manipulation

我有一系列日期 - 比如说2012-01-30 .. 2012-04-06 - 它表示在这些日期之内的一系列日期。这几周的编号为1到10.鉴于今天的日期(例如,2012-02-29),我希望能够得到范围内的周数(在本例中为5)。我如何在Perl中实现这一目标?

3 个答案:

答案 0 :(得分: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";
}

您只需要计算您所在范围内的唯一周数。

答案 1 :(得分:1)

除非您想要合并某些值检查,否则结束日期的值不会产生任何差异。您需要的值是周(开始日期) - 周(此日期)+ 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

答案 2 :(得分: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;