Home > Back-end >  Get correct week number from date (first days of year must not return 52)
Get correct week number from date (first days of year must not return 52)

Time:07-10

Let's say I have date 2022-01-02 and when I want to use W to get the week of the year, I get 52. It's the 52nd week of year 2021, but not actually in 2022.

My question is: How can I get the right year of week from this date?

$date = "2022-01-02 00:00:00";
$week = (float) date("W", strtotime($date));
print $week . "\n";

CodePudding user response:

Week 52 of year 2021 started at 2021-12-27 (a Monday) and ended at 2022-01-02 (a Sunday). Week 1 of year 2022 started at 2022-01-03 (a Monday). This is the definition by ISO 8601. Such a numbering of the weeks is used, for example, in international merchandise management.

For this, date() support 3 format characters:

  • w for week day
  • W for the week number
  • o for the year related to W

So echo date("o W w",strtotime("2022-01-02 00:00")); prints 2021 52 0 (year, week, day of week). The day-of-week follows the old idea, where Sunday is the first day of the week. The the week days are numbered 1 2 3 4 5 6 0.

CodePudding user response:

Because your requirement is different from the ISO 8601 definition of "week" in s year, I recommend calculating the week number manually.

Find the difference (in days) between the supplied date and the zero-second time of the first day of the same year. Divide that number by 7, floor() that number to truncate the decimals, then add 1 (to the result so that the week number does not start from zero.

Code: (Demo)

$date = "2022-01-02 00:00:00";

$startOfYear = DateTime::createFromFormat('!Y ', $date);
var_export(
    1   (int) ($startOfYear->diff(new DateTime($date))->days / 7)
);
  • Related