What is the purpose of DateInterval and DatePeriod classes in PHP when working with dates?
When working with dates in PHP, the DateInterval class is used to represent a time interval between two dates, allowing for easy addition or subtraction of time periods. The DatePeriod class, on the other hand, is used to iterate over a set of dates within a specified interval, making it useful for tasks such as generating a range of dates for a given period.
// Example of using DateInterval and DatePeriod classes in PHP
$startDate = new DateTime('2022-01-01');
$endDate = new DateTime('2022-01-31');
$interval = new DateInterval('P1D'); // 1 day interval
$period = new DatePeriod($startDate, $interval, $endDate);
foreach ($period as $date) {
echo $date->format('Y-m-d') . "\n";
}