Last active
April 9, 2021 12:25
-
-
Save MattStrauss/c001b733d9ec942ea403c6adbdd4dcd8 to your computer and use it in GitHub Desktop.
Count number of day occurrences in a given period with Nesbot Carbon and PHP/Laravel
This file contains hidden or 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
/** | |
* @param $timePeriod | |
* @param $day | |
* | |
* @return int | |
*/ | |
private function getNumberOfSpecificDaysInPeriod($timePeriod, $day) | |
{ | |
$numberOfDaysInPeriod = $this->geDaysInPeriod($timePeriod) - 1; | |
$dynamicDayVariable = 'is'. $day; | |
$startOfPeriod = Carbon::now()->subDays($numberOfDaysInPeriod); | |
return $startOfPeriod->diffInDaysFiltered(function ($date) use ($dynamicDayVariable) { | |
return $date->$dynamicDayVariable(); | |
}, Carbon::now()); | |
} | |
/** | |
* @param $timePeriod | |
* | |
* @return int | |
*/ | |
private function getDaysInPeriod($timePeriod) | |
{ | |
switch ($timePeriod) { | |
case 'week': | |
$days = 7; | |
break; | |
case 'month': | |
$days = 30; | |
break; | |
case 'quarter': | |
$days = 92; | |
break; | |
case 'year': | |
$days = 365; | |
break; | |
default: | |
$days = 1; | |
} | |
return $days; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by: https://gist.github.com/depsimon/22260e7106dfa961c6a37e12d0386082
https://carbon.nesbot.com/docs/