How to get all Dates between two Dates in PHP
Today, we will show you how to get all Dates between two Dates in PHP. Here, we get the all dates array between the given start and end date which can be used to get reports between two dates by daily, weekly, monthly, or yearly. we explain two different methods with simple example to return the dates in array.
Checkout more articles on PHP
Ways to get all dates between two dates
1. Using strtotime() function
In this method, we will use the strtotime() function to get the all dates between two dates.
We will create a function which contains only start date and end date parameters, that returns the array of dates between two dates.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php function getBetweenDates($startDate, $endDate) { $rangArray = []; $startDate = strtotime($startDate); $endDate = strtotime($endDate); for ($currentDate = $startDate; $currentDate <= $endDate; $currentDate += (86400)) { $date = date('Y-m-d', $currentDate); $rangArray[] = $date; } return $rangArray; } $dates = getBetweenDates('2022-07-01', '2022-07-09'); print_r($dates); ?> |
2. Using date interval class
Let’s use the following code to get the list of dates between two dates using date interval class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php function getBetweenDates($startDate, $endDate) { $array = array(); $interval = new DateInterval('P1D'); $realEnd = new DateTime($endDate); $realEnd->add($interval); $period = new DatePeriod(new DateTime($startDate), $interval, $realEnd); foreach($period as $date) { $array[] = $date->format('Y-m-d'); } return $array; } $dates = getBetweenDates('2022-07-01', '2022-07-09'); print_r($dates); ?> |
Output
You will get the following output.
1 2 3 4 5 6 7 8 9 10 11 12 | Array ( [0] => 2022-07-01 [1] => 2022-07-02 [2] => 2022-07-03 [3] => 2022-07-04 [4] => 2022-07-05 [5] => 2022-07-06 [6] => 2022-07-07 [7] => 2022-07-08 [8] => 2022-07-09 ) |
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂