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?
Asked
Active
Viewed 1,092 times
0
-
Do your weeks start on Monday? Will the date range always start on a Mondaya and end on a Friday? – Borodin Jan 28 '12 at 13:37
3 Answers
3
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.

yko
- 2,710
- 13
- 15
-
This is a neat solution, but requires me to expand the array `@dates` and iterate over it, counting unique weeks. Yes, it works, and doesn't require any non-core modules, but my preference is for a smaller (in terms of code) solution. – Jashank Jeremy Jan 28 '12 at 23:17
1
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

Borodin
- 126,100
- 9
- 70
- 144
-
1If it matters to the user, Date::Calc isn't a core module, while Time::Piece has been since v5.9.5 – JRFerguson Jan 28 '12 at 14:19
-
@JRFerguson: Since I already use `Date::Calc`, it's not really an issue. – Jashank Jeremy Jan 28 '12 at 23:14
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;

daxim
- 39,270
- 4
- 65
- 132