Home >Backend Development >PHP Tutorial >How to Calculate and Format the Difference Between Two Datetimes as 'Y-m-d H:i:s'?
Calculating the Difference Between Two Datetimes in Y-m-d H:i:s Format
Determining the time difference between two datetimes is a common task in many programming scenarios. However, it's crucial to understand how to format the difference in a specific format.
In the given case, the user wants to find the difference between two datetimes and format it as "Y-m-d H:i:s". The provided code snippet uses the diff() method, but it's not formatted correctly.
To achieve the desired format, we can utilize the DateTime class. Here's an example:
$datetime1 = new DateTime(); $datetime2 = new DateTime('2011-01-03 17:13:00'); $interval = $datetime1->diff($datetime2); $elapsed = $interval->format('%Y-%m-%d %H:%i:%s'); echo $elapsed;
In this example:
By using this approach, you can obtain the difference between two datetimes and format it in the specified format.
The above is the detailed content of How to Calculate and Format the Difference Between Two Datetimes as 'Y-m-d H:i:s'?. For more information, please follow other related articles on the PHP Chinese website!