How can you improve date calculations in PHP by using DateTime instead of strtotime and date functions?

When working with date calculations in PHP, using the DateTime class provides a more reliable and flexible way to handle dates compared to using strtotime and date functions. DateTime allows for easier manipulation of dates, time zones, and date differences. By using DateTime, you can avoid common pitfalls and errors that may occur when using strtotime and date functions.

// Using DateTime for date calculations
$startDate = new DateTime('2022-01-01');
$endDate = new DateTime('2022-01-31');

// Calculate the difference between two dates
$interval = $startDate->diff($endDate);
echo $interval->format('%a days'); // Output: 30 days

// Add days to a date
$startDate->add(new DateInterval('P10D'));
echo $startDate->format('Y-m-d'); // Output: 2022-01-11