0

Lets say i have date 2022-01-02 and when I want to get week of year I´ve got 52. But its the 52 week of year 2021, not 2022. So 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";
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Dan Rais
  • 159
  • 2
  • 10
  • How do you define "the right week"? For example, in 2022, when was the first day of week #2, for you: the 3rd or the 8th? – Blackhole Jul 09 '22 at 21:35
  • Relevant: [Get week number (in the year) from a date PHP](https://stackoverflow.com/q/9567673/2943403) – mickmackusa Jul 10 '22 at 04:41
  • I rolled back my edit because I believe 1. I didn't understand the question and 2. my edit only made your question less clear. – mickmackusa Jul 10 '22 at 12:14
  • [This specific answer](https://stackoverflow.com/a/27460888/2943403) holds the resolving advice. – mickmackusa Jul 10 '22 at 12:21

1 Answers1

1

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.

Wiimm
  • 2,971
  • 1
  • 15
  • 25