Skip to content

Instantly share code, notes, and snippets.

@andrewrjones
Created October 8, 2010 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewrjones/617021 to your computer and use it in GitHub Desktop.
Save andrewrjones/617021 to your computer and use it in GitHub Desktop.
date-from-week-number.pl
#!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
@denny
Copy link

denny commented Feb 27, 2013

Handy, cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment