Skip to content

Instantly share code, notes, and snippets.

@ngekoding
Last active January 20, 2021 01:31
Show Gist options
  • Save ngekoding/c3d304c6f5978999fcdcfe9c7e61398a to your computer and use it in GitHub Desktop.
Save ngekoding/c3d304c6f5978999fcdcfe9c7e61398a to your computer and use it in GitHub Desktop.
Getting date start & end for every week (Mon - Sun) by given month
<?php
$weeks = get_week_dates('2021-01');
var_dump($weeks);
// Output:
// array(5) {
// [0]=>
// array(2) {
// ["start"]=>
// string(10) "2021-01-01"
// ["end"]=>
// string(10) "2021-01-03"
// }
// [1]=>
// array(2) {
// ["start"]=>
// string(10) "2021-01-04"
// ["end"]=>
// string(10) "2021-01-10"
// }
// [2]=>
// array(2) {
// ["start"]=>
// string(10) "2021-01-11"
// ["end"]=>
// string(10) "2021-01-17"
// }
// [3]=>
// array(2) {
// ["start"]=>
// string(10) "2021-01-18"
// ["end"]=>
// string(10) "2021-01-24"
// }
// [4]=>
// array(2) {
// ["start"]=>
// string(10) "2021-01-25"
// ["end"]=>
// string(10) "2021-01-31"
// }
// }
<?php
/**
* @author Nur Muhammad<blog.nurmuhammad@gmail.com>
*
* @param $month The month to process, format: Y-m (e.g. 2021-01)
* @return array
*/
function get_week_dates($month)
{
$start = new DateTime($month.'-01');
$end = new DateTime();
$end->setDate($start->format('Y'), $start->format('m'), $start->format('t'));
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
$weeks = array();
$week_key = 0;
$first = true;
foreach ($period as $dt) {
if ($first) {
$weeks[$week_key]['start'] = $dt->format('Y-m-d');
$first = false;
}
if ($dt->format('D') == 'Sun' || $dt->format('d') == $end->format('d')) {
$weeks[$week_key]['end'] = $dt->format('Y-m-d');
$week_key++;
$first = true;
}
}
return $weeks;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment