Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

datetime

perl

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?

like image 809
Ethan Brown Avatar asked Feb 23 '12 23:02

Ethan Brown


2 Answers

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";
like image 55
cjm Avatar answered Sep 19 '22 21:09

cjm


Try:

use Date::Calc qw(:all);

my $year = 2012;
my $week = 14;
my ($year2, $month, $day) = Monday_of_Week($week, $year);
like image 43
DVK Avatar answered Sep 18 '22 21:09

DVK