Last active
July 16, 2020 14:42
-
-
Save KaiCMueller/46690cdf58752fada058bb63c540ce0d to your computer and use it in GitHub Desktop.
Get year and week number as 6 digit integer from any DateTime object including fix for in between the years
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @param \DateTime $dateTime | |
* | |
* @return int - e.g. 202001 | |
*/ | |
protected function getCalendarYearWeek(DateTime $dateTime): int | |
{ | |
$week = $dateTime->format('W'); | |
// the calendar week starts on monday | |
$dateTime->modify('monday this week'); | |
// on first week (1) and last week (52 or 53) of the year monday and sunday can be in different years. | |
// the actual year of the current calendar week is depending on which year has more days in this week. | |
if ($week == $this->getLastCalendarWeek($dateTime) || $week == 1) { | |
$checkDateTime = clone $dateTime; | |
// if thursday is in the new year (1/2/3/4) | |
// we switch the day to sunday to set the new year | |
if ($checkDateTime->modify('thursday this week')->format('d') <= 4) { | |
$dateTime->modify('sunday this week'); | |
} | |
} | |
return (int)$dateTime->format('Y') . sprintf('%02d', $week); | |
} | |
/** | |
* @param \DateTime $dateTime | |
* | |
* @return int | |
*/ | |
protected function getLastCalendarWeek(DateTime $dateTime): int | |
{ | |
$dateTime = clone $dateTime; | |
$dateTime->setISODate($dateTime->format('Y'), 53); | |
return ($dateTime->format('W') === '53' ? 53 : 52); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was thinking about a solution for the problem that depending on the weekday the datetime object can return different years for the same calendar week. Whether the current calendar week counts into the old or the new year depends on the first thursday of the year, see: https://en.wikipedia.org/wiki/ISO_week_date#First_week
Maybe I overcomplicated things here while trying to solve the puzzle. If you can think about a more elegant solution please let me know!