Reputation: 699
Is there any PHP function to display all dates between two dates?
Upvotes: 10
Views: 20740
Reputation: 662
$start_date = '2020/09/01';
$end_date = '2020-09-03';
$new_date = new DateTime($end_date);
$new_date->add(new DateInterval('P1D'));
$end_date = $new_date->format('Y-m-d');
$period = new DatePeriod(
new DateTime($start_date),
new DateInterval('P1D'),
new DateTime($end_date)
);
print_r($period);
foreach ($period as $key => $value) {
echo $value->format('Y-m-d') .'<br>';
}
Print:
2020-09-01
2020-09-02
2020-09-03
Upvotes: 1
Reputation: 4305
You can check out this function also
$day = 86400; // Day in seconds
$format = 'Y-m-d'; // Output format (see PHP date funciton)
$sTime = strtotime($start_date); // Start as time
$eTime = strtotime($end_date); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();
for ($d = 0; $d < $numDays; $d++) {
$days[] = date($format, ($sTime + ($d * $day)));
}
Upvotes: 4
Reputation: 24551
There is the DatePeriod
class.
EXAMPLE:
$begin = new DateTime('2013-02-01');
$end = new DateTime('2013-02-13');
$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);
foreach($daterange as $date){
echo $date->format("Y-m-d") . "<br>";
}
(P1D stands for period of one day, see DateInterval
for further documentation)
Upvotes: 31