Home > Article > Backend Development > How to calculate the difference between two times in php
Method: 1. Use the strtotime() function to format the two specified times into timestamps. The syntax is "strtotime (specified time)"; 2. Subtract the two timestamps to obtain two The time difference in seconds; 3. Convert the time difference in seconds into a time difference in days. The syntax is "time difference in seconds/86400".
The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer
1. Use the strtotime function to format time into a timestamp
strtotime() function parses the date or time description of any English text into a Unix timestamp (since January 1 seconds since 1970 00:00:00 GMT).
The syntax is:
strtotime('年-月-日 时:分:秒')
The example is as follows:
<?php echo(strtotime('2022-04-13 12:25:00')); ?>
Output result:
2. Subtract the two timestamps to get the time difference between the two times
3. Divide the obtained time difference by 86400 to get the number of days difference between the two times
Examples are as follows:
<?php $time1=strtotime('2022-04-13 12:25:00'); $time2=strtotime('2022-04-15 12:25:00'); $diff_seconds = $time2 - $time1; $diff_days = $diff_seconds/86400; echo($diff_days . "天"); ?>
Output results:
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to calculate the difference between two times in php. For more information, please follow other related articles on the PHP Chinese website!