How can PHP be used to format dates and calculate time intervals accurately?

To format dates and calculate time intervals accurately in PHP, you can use the DateTime class. This class provides various methods for formatting dates, calculating time intervals, and performing date/time arithmetic. By creating DateTime objects and utilizing its methods, you can easily achieve accurate date and time calculations in PHP.

// Format a date
$date = new DateTime('2022-01-01');
$formattedDate = $date->format('Y-m-d'); // Output: 2022-01-01

// Calculate time interval
$interval = new DateInterval('P1D'); // 1 day interval
$date->add($interval); // Add 1 day to the date
$newDate = $date->format('Y-m-d'); // Output: 2022-01-02