Skip to content

Instantly share code, notes, and snippets.

@MattStrauss
Last active April 9, 2021 12:25
Show Gist options
  • Save MattStrauss/c001b733d9ec942ea403c6adbdd4dcd8 to your computer and use it in GitHub Desktop.
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
/**
* @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;
}
@MattStrauss
Copy link
Author

MattStrauss commented Apr 5, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment