To find the number of days between two dates in PHP, you can use the DatePeriod
class. This class allows you to iterate over a set of days between two dates, with a specified interval.
Here’s an example of how you can use it:
$start = new DateTime('2022-01-01');
$end = new DateTime('2022-12-31');
$interval = new DateInterval('P1D'); // P1D means a period of 1 day
$period = new DatePeriod($start, $interval, $end);
$count = count($period); //Outputs: 366
This code creates a DatePeriod
object that starts on January 1, 2022, ends on December 31, 2022, and has a 1-day interval. It then iterates over the period and counts the number of dates.
Note that the DatePeriod
class handles time zones and daylight saving time, so you don’t need to worry about those when counting the number of dates between two dates.