To calculate the time difference between two dates in PHP, you can use the DateTime class along with the diff() method. Here’s an example code snippet:
$date1 = new DateTime('2023-02-25 10:30:00');
$date2 = new DateTime('2023-02-26 12:00:00');
$interval = $date1->diff($date2);
echo $interval->format('%d days, %h hours, %i minutes, %s seconds');
In this example, we’re starting with two dates: ‘2023-02-25 10:30:00’ and ‘2023-02-26 12:00:00’. The DateTime objects are created using the initial date strings.
The diff() method is then called on the first DateTime object, with the second DateTime object passed as an argument. This calculates the difference between the two dates as a DateInterval object.
Finally, the format() method is called on the DateInterval object to format the resulting time difference string. The format string ‘%d days, %h hours, %i minutes, %s seconds’ represents the number of days, hours, minutes, and seconds in the time difference.
The output of the example code snippet will be ‘1 days, 1 hours, 30 minutes, 0 seconds’, which represents the time difference between the two dates.