What are some common methods to calculate time differences in PHP?

Calculating time differences in PHP involves comparing two dates or timestamps and determining the difference in seconds, minutes, hours, or days between them. Some common methods to calculate time differences in PHP include using the strtotime() function to convert dates to timestamps, then subtracting one timestamp from another to get the difference in seconds, and using the date_diff() function to calculate the difference between two DateTime objects.

// Method 1: Using strtotime() function
$date1 = strtotime('2022-01-01 12:00:00');
$date2 = strtotime('2022-01-01 13:30:00');
$timeDiffInSeconds = $date2 - $date1;
echo "Time difference in seconds: " . $timeDiffInSeconds;

// Method 2: Using DateTime objects and date_diff() function
$dateObj1 = new DateTime('2022-01-01 12:00:00');
$dateObj2 = new DateTime('2022-01-01 13:30:00');
$timeDiff = $dateObj1->diff($dateObj2);
echo "Time difference: " . $timeDiff->format('%h hours %i minutes');