PHP calculates the two time difference and returns the number of days, hours, minutes, and seconds.

Source: Internet
Author: User
Tags echo date

Function timediff ($ begin_time, $ end_time)
{
If ($ begin_time <$ end_time ){
$ Starttime = $ begin_time;
$ Endtime = $ end_time;
}
Else {
$ Starttime = $ end_time;
$ Endtime = $ begin_time;
}
$ Timediff = $ endtime-$ starttime;
$ Days = intval ($ timediff/86400 );
$ Remain = $ timediff % 86400;
$ Hours = intval ($ remain/3600 );
$ Remain = $ remain % 3600;
$ Mins = intval ($ remain/60 );
$ Secs = $ remain % 60;
$ Res = array ("day" => $ days, "Hour" => $ hours, "min" => $ mins, "Sec" => $ SECs );
Return $ res;
}

 

 

 

========================================================== ========================================================== =

Another method:

When using PHP programming, we may need to compare two time differences. If the comparison is passed directly, there will be problems. Therefore, we need to use the strtotime () function to control the difference. The specific method is as follows:

Assume that the two time periods to be compared are$ Htmer1And$ Htmer2First, use the strtotime () function to calculate the timestamps of the two time ranges. (For more information about timestamps, see:What is a timestamp?), And then use the followingCodeComparison:

$ Times = strtotime (& htmer2)-strtotime ($ htmer1)// Calculate the two time difference to obtain the number of seconds for the difference
$ TimeI = round (times/60)// The number of minutes of the difference can be obtained. Round () is rounded to five.

The above code completes the comparison between two time points. You can perform specific operations based on the actual situation. Next we will introduce the reverse operation of strtotime (). You can use the following code to perform a test.

echo strtotime ("08:08:08"); // calculate the 08:08:08 timestamp
echo"
";
echo date (" Y-m-d h: i: s ", strtotime (" 08:08:08 "); // calculate the specific time according to the timestamp calculated above
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.