Home >Backend Development >PHP Tutorial >How to Calculate and Format Datetime Differences in Y-m-d H:i:s in PHP?
Calculating Datetime Differences and Formatting in Y-m-d H:i:s
Determining the time elapsed between two datetimes is essential in various programming scenarios. In PHP, the diff() method offers a straightforward solution, although it requires specific formatting to obtain the desired output format of "Y-m-d H:i:s."
To calculate the difference between two datetimes, instantiate two DateTime objects and use the diff() method on one object with the other as an argument. The result will be a DateInterval object containing the difference between the two datetimes.
Formatting the DateInterval object to the desired format requires the format() method with the appropriate format string. For example, to format the difference in years, months, days, hours, minutes, and seconds, use the following format string: '%y years %m months %a days %h hours %i minutes %s seconds'.
Here's an example code demonstrating the calculation and formatting of the datetime difference:
$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;
Running this code will output the time elapsed in the specified format. Remember to replace '2011-01-03 17:13:00' with the datetime value you want to calculate the difference for.
The above is the detailed content of How to Calculate and Format Datetime Differences in Y-m-d H:i:s in PHP?. For more information, please follow other related articles on the PHP Chinese website!