Question

I have a range of dates -- say 2012-01-30 .. 2012-04-06 -- which denote a set of weeks that fall within these dates. These weeks are numbered 1 through 10. Given today's date (for instance, 2012-02-29), I want to be able to get the week number within the range (in this case, 5). How do I achieve this in Perl?

Was it helpful?

Solution

The value of the end date doesn't make any difference unless you want to incorporate some value checking. The value that you need is week(start date) - week(this date) + 1. I recommend the Date::Calc module for its tidiness and efficiency. The code looks like this

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";

OUTPUT

5

OTHER TIPS

Package Time::Piece has strptime method to parse string into a time object and week method to indicate number of the week of the time object.

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";
}

All you need to do is just to count number of unique weeks in your range.

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top