Skip to main content

Getting the date from the ISO week number in Perl

·2 mins

The code below allows you to get the date at the start of the week given the ISO Week Number and optionally the year (defaulting to this year), and requires the DateTime module.

#!perl

use POSIX;
use DateTime;
use Test::More tests => 3;

sub date_from_week_number {
    my ( $week_num, $year ) = @_;
    $year ||= POSIX::strftime( '%Y', localtime );

    return DateTime->from_day_of_year(
        day_of_year => 4,
        year        => $year,
    )->add( weeks => $week_num - 1 )->truncate( to => 'week' );
}

my $dt = date_from_week_number( 40, 2010 );
is( $dt->ymd, '2010-10-04', 'week 40, year 2010' );
$dt = date_from_week_number( 24, 2009 );
is( $dt->ymd, '2009-06-08', 'week 24, year 2009' );
$dt = date_from_week_number( 20, 2012 );
is( $dt->ymd, '2012-05-14', 'week 20, year 2012 (leap year)' );

__END__
=head1 date-from-week-number.pl
This is an example of how to get the date from a week number and an optional year (defaulting to this year).
=head1 COPYRIGHT
Copyright (c) 2010 Andrew Jones 
- L<http://andrew-jones.com>
=head1 LICENSE
This code is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut

The first week of the year is defined by ISO as the one which contains the fourth day of January, which is why we get the fourth day of the year before working out which week we are interested in.

This subroutine will return the date at the start of the week, as a DateTime object. Feel free to take the code and use or modify it as you need.