Home  >  Article  >  Backend Development  >  How to calculate the difference between two times in php

How to calculate the difference between two times in php

WBOY
WBOYOriginal
2022-04-13 15:33:389888browse

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".

How to calculate the difference between two times in php

The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer

How does php calculate the difference between two times

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(&#39;2022-04-13 12:25:00&#39;)); 
?>

Output result:

How to calculate the difference between two times in php

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(&#39;2022-04-13 12:25:00&#39;); 
$time2=strtotime(&#39;2022-04-15 12:25:00&#39;); 
$diff_seconds = $time2 - $time1;
$diff_days = $diff_seconds/86400;
echo($diff_days . "天");
?>

Output results:

6How to calculate the difference between two times in php

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn