When you want to pull the dates between two dates, where the between dates are connecting dots. If you want to list the complete date ranges through months. For example, to find the dates between below dates
date1 = '2022-12-29';
date2 = '2023-02-20';
expected output would be
Start Date | End Date |
---|---|
2022-12-29 | 2022-12-31 |
2023-01-01 | 2023-01-31 |
2023-02-01 | 2023-02-20 |
<?php
/*
* Returns array of month's start & end dates between provided dates.
*
* @param string $start_date
* @param string $end_date
*
*
* @return array
*/
function getDates($start_date, $end_date){
$start_date_obj = new DateTime($start_date);
$end_date_obj = new DateTime($end_date);
$diff = $end_date_obj->diff($start_date_obj);
$months = (($diff->y) * 12) + ($diff->m);
$dates[] = array('start_date' => $start_date, 'end_date' => date('Y-m-t', strtotime($start_date)), 'suffix' => date('Y-m', strtotime($start_date)));
$new_start_date = strtotime(date('Y-m-01', strtotime($start_date)));
for($i = 1; $i <= $months; $i++){
$new_start_date = strtotime("+1 months", $new_start_date);
$dates[] = array('start_date' => date('Y-m-01', $new_start_date), 'end_date' => date('Y-m-t', $new_start_date) , 'suffix' => date('Y-m', $new_start_date));
}
$dates[] = array('start_date' => date('Y-m-01', strtotime($end_date)), 'end_date' => $end_date, 'suffix' => date('Y-m', strtotime($end_date)));
return $dates;
}
$start_date = '2022-12-29';
$end_date = '2023-02-20';
$dates = getDates($start_date, $end_date);
print_r($dates);
?>
Output:
Array ( [0] => Array ( [start_date] => 2022-12-29 [end_date] => 2022-12-31 [Ym] => 2022-12 ) [1] => Array ( [start_date] => 2023-01-01 [end_date] => 2023-01-31 [Ym] => 2023-01 ) [2] => Array ( [start_date] => 2023-02-01 [end_date] => 2023-02-20 [Ym] => 2023-02 ) )
Comments
Post a Comment
Want to tell something about this post. Please feel free to write...