diff --git a/src/php-8.1-strftime.php b/src/php-8.1-strftime.php index 0846c35..158470d 100644 --- a/src/php-8.1-strftime.php +++ b/src/php-8.1-strftime.php @@ -121,14 +121,12 @@ function strftime (string $format, $timestamp = null, ?string $locale = null) : // Week '%U' => function ($timestamp) { // Number of weeks between date and first Sunday of year - $day = new DateTime(sprintf('%d-01 Sunday', $timestamp->format('Y'))); - return sprintf('%02u', 1 + ($timestamp->format('z') - $day->format('z')) / 7); + return sprintf('%02u', intdiv((int) $timestamp->format('z') + 7 - (int) $timestamp->format('w'), 7)); }, '%V' => 'W', '%W' => function ($timestamp) { // Number of weeks between date and first Monday of year - $day = new DateTime(sprintf('%d-01 Monday', $timestamp->format('Y'))); - return sprintf('%02u', 1 + ($timestamp->format('z') - $day->format('z')) / 7); + return sprintf('%02u', intdiv((int) $timestamp->format('z') + 7 - ((int) $timestamp->format('w') + 6) % 7, 7)); }, // Month diff --git a/tests/strftimeTest.php b/tests/strftimeTest.php index c1e19fb..4dceef6 100644 --- a/tests/strftimeTest.php +++ b/tests/strftimeTest.php @@ -73,6 +73,15 @@ public function testWeekFormats () { $result = strftime('%W', '20220306 13:02:03'); $this->assertEquals('09', $result, '%W: A numeric representation of the week of the year, starting with the first Monday as the first week'); + + $result = strftime('%U', new DateTime('0999-12-31 00:00:00')); + $this->assertEquals('52', $result, '%U: Week number of a year before 1000'); + + $result = strftime('%W', new DateTime('0999-12-31 00:00:00')); + $this->assertEquals('52', $result, '%W: Week number of a year before 1000'); + + $result = strftime('%W', new DateTime('0001-01-01 00:00:00')); + $this->assertEquals('01', $result, '%W: Week number of a year that starts on a Monday'); } public function testMonthFormats () {