hhy
hhy

Reputation: 55

Get week of year (the first day of week is Sunday) could not return week 53

use strict;
use Time::Local;
use POSIX qw(strftime);

my $date = '12/31/1899';
my ($month, $day, $year) = split '/', $date;

my $epoch = timelocal( 0, 0, 0, $day, $month - 1, $year - 1900 );
my $week  = strftime( "%U", localtime( $epoch ) );

printf "Date: %s Week: %s\n", $date, $week;

=> Date: 12/31/1899 Week: 53

However when $date = '12/30/1900', it return week 52 not week 53.

Could you please help me to point out the problem? Thanks.

Upvotes: 1

Views: 164

Answers (1)

ikegami
ikegami

Reputation: 385917

%U

The week number of the current year as a decimal number, range 00 to 53, starting with the first Sunday as the first day of week 01. See also %V and %W.

By that definition, 1900-12-30 is part of week 52.

You can verify this yourself using a calendar of 1900.

  • Week 0 of 1900: Mon, Jan 1, 1900 to Sat, Jan 6, 1900
  • Week 1 of 1900: Sun, Jan 7, 1900 to Sat, Jan 13, 1900
  • ...
  • Week 51 of 1900: Sun, Dec 23, 1900 to Sat, Dec 29, 1900
  • Week 52 of 1900: Sun, Dec 30, 1900 to Mon, Dec 31, 1900

That said, it's a fluke that you are getting the right answer (52). You are passing 0 ($year - 1900) as the last argument to timelocal, and that refers to the year 2000, not the year 1900.

This explains why you were getting 53 for 12/31/1900. While 1900-12-31 is in week 52, 2000-12-31 starts week 53.

To fix this, replace

timelocal( 0, 0, 0, $day, $month - 1, $year - 1900 )

with

timelocal( 0, 0, 0, $day, $month - 1, $year )

Upvotes: 6

Related Questions