To list week's start date & end date between given two dates. It also includes number of dates in every set. It allows you to list only those weeks having total seven days. Here the starting day of the week is Monday & the end day of the week is Sunday.
Here is the example:/*
* Returns array of week's start & end dates with number of days between those.
*
* @param string $start_date
* @param string $end_date
* @param boolean $only_full_week
*
* @return array
*/
function getWeekDates($start_date, $end_date, $only_full_week = false)
{
$stime = strtotime($start_date);
$etime = strtotime($end_date);
$weeks = array();
$i = 0;
$j = 1;
while ($stime <= $etime) {
if ($i == 0 && $j == 1) {
$weeks[$i]['start_date'] = date('Y-m-d', $stime);
$weeks[$i]['end_date'] = date('Y-m-d', $stime);
$weeks[$i]['count'] = $j;
} else if (date('N', $stime) == 1) {
$j = 1;
$weeks[$i]['start_date'] = date('Y-m-d', $stime);
$weeks[$i]['end_date'] = date('Y-m-d', $stime);
$weeks[$i]['count'] = $j;
}
if (date('N', $stime) == 7) {
$weeks[$i]['end_date'] = date('Y-m-d', $stime);
$weeks[$i]['count'] = $j;
$i ++;
}
$j ++;
$stime = strtotime('+1 day', $stime);
}
if ($only_full_week) {
foreach ($weeks as $key => $week) {
if ($week['count'] != 7) {
unset($weeks[$key]);
}
}
}
return array_values($weeks);
}
$start_date = '2018-12-23';
$end_date = '2019-01-08';
print_r(getWeekDates($start_date, $end_date));
Output:Array
(
[0] => Array
(
[start_date] => 2018-12-23
[end_date] => 2018-12-23
[count] => 1
)
[1] => Array
(
[start_date] => 2018-12-24
[end_date] => 2018-12-30
[count] => 7
)
[2] => Array
(
[start_date] => 2018-12-31
[end_date] => 2019-01-06
[count] => 7
)
[3] => Array
(
[start_date] => 2019-01-07
[end_date] => 2019-01-07
[count] => 1
)
)
If we need only full weeks, include the third parameter as 'true'
$start_date = '2018-12-23';
$end_date = '2019-01-08';
print_r(getWeekDates($start_date, $end_date, true));
Output:Array
(
[0] => Array
(
[start_date] => 2018-12-24
[end_date] => 2018-12-30
[count] => 7
)
[1] => Array
(
[start_date] => 2018-12-31
[end_date] => 2019-01-06
[count] => 7
)
)
Comments
Post a Comment
Want to tell something about this post. Please feel free to write...