This article mainly introduces the method of time comparison and time difference calculation in PHP, involving PHP date and time conversion, calculation and other related operation skills. Friends in need can refer to it
The examples of this article describe PHP Method to implement time comparison and time difference calculation. Share it with everyone for your reference, the details are as follows:
Example 1:
<?php //PHP时间比较和时间差计算: //(1).比较两个绝对时间的大小 header("Content-type: text/html; charset=utf-8"); date_default_timezone_set('PRC'); $zero1=date("Y-m-d h:i:s"); //$zero1="2010-11-29 21:07:00"; $zero2="2010-11-29 21:07:00"; echo "zero1的时间为:".$zero1."<br>"; echo "zero2的时间为:".$zero2."<br>"; // strtotime — 将任何英文文本的日期时间描述解析为 Unix 时间戳 if(strtotime($zero1)<strtotime($zero2)){ echo "zero1早于zero2"; }else if(strtotime($zero1)>strtotime($zero2)){ echo "zero2早于zero1"; }else{ echo "zero2等于zero1"; } echo "<br/><br/>"; ?>
Running results:
zero1的时间为:2017-07-24 12:18:39 zero2的时间为:2010-11-29 21:07:00 zero2早于zero1
Example 2:
<?php //(2).倒计时小程序 $zero1=strtotime (date("y-m-d h:i:s")); //当前时间 ,注意H 是24小时 h是12小时 $zero2=strtotime ("2018-1-1 00:00:00"); //过年时间 //float ceil ( float $value ) //返回不小于 value 的下一个整数,value 如果有小数部分则进一位。 $guonian=ceil(($zero2-$zero1)/86400); //60s*60min*24h echo "离过年还有<strong>$guonian</strong>天!"; echo "<br/><br/>"; ?>
Running result:
离过年还有161天
Example 3:
<?php //(3).PHP计算两个时间差的方法 $startdate=date("y-m-d H:i:s"); $enddate="2017-7-30 18:00:00"; // floor — 舍去法取整 // float floor ( float $value ) // 返回不大于 value 的最接近的整数,舍去小数部分取整。 $date=floor((strtotime($enddate)-strtotime($startdate))/86400); $hour=floor((strtotime($enddate)-strtotime($startdate))%86400/3600); $minute=floor((strtotime($enddate)-strtotime($startdate))%86400/60); $second=floor((strtotime($enddate)-strtotime($startdate))%86400%60); echo "现在距结束时间还有".$date."天".$hour."小时".$minute."分钟".$second."秒"; echo "<br/><br/>"; ?>
Running result:
现在距结束时间还有6天5小时339分钟56秒
Related recommendations:
PHP calculationTime difference
JS calculation dateTime difference
JavaScript implementation of dateJudgement of time difference
##
The above is the detailed content of PHP method to implement time comparison and time difference calculation (example). For more information, please follow other related articles on the PHP Chinese website!