Week numbers in PHP
How to get the week number from a date
To get the ISO week number (1-53) of a date represented by a Unix timestamp, use idate('W', $timestamp)
or strftime('%-V', $timestamp)
.
For a date represented by a DateTime instance, use intval($dateTime->format('W'))
. Note that format() returns the week number zero-prefixed (e.g. 05), so you need intval to strip the leading zero.
To get the corresponding four-digit year (e.g. 2023), use idate('o', $timestamp)
or strftime('%G', $timestamp)
or $dateTime->format('o')
.
Read more about strftime(), idate() and DateTime::format() in the PHP manual.
How to get the date from a week number
To get the Unix timestamp representing the start of the week (Monday at midnight), use strtotime(sprintf("%4dW%02d", $year, $week))
.
$year is a 4-digit year (e.g. 2023), and $week is an ISO week number (1-53). The sprintf() call generates a week string in ISO 8601 format, e.g. "2023W01".
To get the start of the week as a DateTime object, use $date = new DateTime('midnight'); $date->setISODate($year, $week);
Read more about strtotime() in the PHP manual.
How to get the number of weeks in a year
To get the number of ISO weeks (i.e. the number of the last week) in a year, use idate('W', mktime(0, 0, 0, 12, 28, $year))
.
This is based on the fact that the last week of the year always includes 28 December.