Anatoliy  Gusarov
Anatoliy Gusarov

Reputation: 808

DateTime 2018 and 2019 week count PHP bug?

Wanted to get maximum weeks in a year, and thought this would be the simplest way to get this number, but I was surprised,that the last day in a year could be in the first week. Is this because these days are in the first half of the week?
So I know how to get the correct number, I'm just wondering about the logic.

<?php
echo (new DateTime('2016-12-31 00:00:00'))->format('W'); //52

echo (new DateTime('2017-12-31 00:00:00'))->format('W'); //52

echo (new DateTime('2018-12-31 00:00:00'))->format('W'); //01
echo (new DateTime('2018-12-30 00:00:00'))->format('W'); //52

echo (new DateTime('2019-12-31 00:00:00'))->format('W'); //01
echo (new DateTime('2019-12-30 00:00:00'))->format('W'); //01
echo (new DateTime('2019-12-29 00:00:00'))->format('W'); //52

echo (new DateTime('2020-12-31 00:00:00'))->format('W'); //53

Found by answered links (Wikipedia):

Last week

The last week of the ISO week-numbering year, i.e. the 52nd or 53rd one, is the week before week 01. This week’s properties are:

It has the year's last Thursday in it.

It is the last week with a majority (4 or more) of its days in December.

Its middle day, Thursday, falls in the ending year.

Its last day is the Sunday nearest to 31 December.

It has 28 December in it. Hence the latest possible dates are 28 December through 3 January, the earliest 21 through 28 December.

If 31 December is on a Monday, Tuesday or Wednesday, it is in week 01 of the next year. If it is on a Thursday, it is in week 53 of the year just ending; if on a Friday it is in week 52 (or 53 if the year just ending is a leap year); if on a Saturday or Sunday, it is in week 52 of the year just ending

Upvotes: 0

Views: 1523

Answers (2)

Perry
Perry

Reputation: 11710

If you want to get the last week of the year you can use this simple function:

function getIsoWeeksInYear($year) {
  $date = new DateTime;
  $date->setISODate($year, 53);
  return ($date->format("W") === "53" ? 53 : 52);
}

Upvotes: 1

orique
orique

Reputation: 1303

It's probably following the ISO week date system. Citing that wikipedia article:

The ISO 8601 definition for week 01 is the week with the year's first Thursday in it.

Upvotes: 3

Related Questions