Skip to content

Instantly share code, notes, and snippets.

@jpSimkins
Last active August 1, 2018 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpSimkins/392b9b6c820a0d98fc3f to your computer and use it in GitHub Desktop.
Save jpSimkins/392b9b6c820a0d98fc3f to your computer and use it in GitHub Desktop.
Returns an array of dates for the day of the week between two date ranges
<?php
/**
* Returns an array of dates for the day of the week between two date ranges
* Modified from stackoverflow question and improved for broader usage
* @link http://stackoverflow.com/a/4482605/650206
* @param string|int $startDate
* @param string|int $endDate
* @param int $weekdayNumber
* @param string $dateFormat
* @param string $dateWeekNumberFormat w: 0 (sunday) - 6 (saturday) | N: 1 (monday) - 7 (sunday)
* @return array
*/
function getDatesForSpecificDayBetweenDates($startDate, $endDate, $weekdayNumber, $dateFormat='Y-m-d', $dateWeekNumberFormat='w') {
// Fix the proper date range, if needed (prevents issues with int in strtotime)
$startDate = !is_int($startDate) ? strtotime($startDate) : $startDate;
$endDate = !is_int($endDate) ? strtotime($endDate) : $endDate;
// Move start date to the proper $weekDayNumber
do {
if (date($dateWeekNumberFormat, $startDate) != $weekdayNumber) {
$startDate += (24 * 3600); // add 1 day
}
} while (date($dateWeekNumberFormat, $startDate) != $weekdayNumber);
// Build dates array
$dateArr = array();
while ($startDate <= $endDate) {
$dateArr[] = date($dateFormat, $startDate);
$startDate += (7 * 24 * 3600); // add 7 days
}
return ($dateArr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment