Ethan Brown
Ethan Brown

Reputation: 703

Perl: Given the year and week number, how can I get the first date in that week?

Using the excellent Perl DateTime module it is trivial to obtain the year and week number for a date, but going the other way seems to be a bit more difficult. How does one go about obtaining a date starting with the year and week number?

Upvotes: 10

Views: 5158

Answers (2)

cjm
cjm

Reputation: 62109

Here's one way to do it using only DateTime:

use DateTime;

sub first_day_of_week
{
  my ($year, $week) = @_;

  # Week 1 is defined as the one containing January 4:
  DateTime
    ->new( year => $year, month => 1, day => 4 )
    ->add( weeks => ($week - 1) )
    ->truncate( to => 'week' );
} # end first_day_of_week


# Find first day of second week of 2012 (2012-01-09):
my $d = first_day_of_week(2012, 2);

print "$d\n";

Upvotes: 14

DVK
DVK

Reputation: 129423

Try:

use Date::Calc qw(:all);

my $year = 2012;
my $week = 14;
my ($year2, $month, $day) = Monday_of_Week($week, $year);

Upvotes: 11

Related Questions