php计算两个时间相差的天数、小时数、分钟数、秒数


$startdate="2011-3-15 11:50:00";//开始时间

$enddate="2012-12-12 12:12:12";//结束时间

$date=floor((strtotime($enddate)-strtotime($startdate))/86400);

echo "相差天数:".$date."天<br><br>";

$hour=floor((strtotime($enddate)-strtotime($startdate))%86400/3600);

echo "相差小时数:".$hour."小时<br><br>";

$minute=floor((strtotime($enddate)-strtotime($startdate))%86400/60);

echo"相差分钟数:".$minute."分钟<br><br>";

$second=floor((strtotime($enddate)-strtotime($startdate))%86400%60);

echo"相差秒数:".$second."秒";

不管是自己使用字符串来构造的时间类型(使用strtotime转换而来的)也好,还是直接使用系统的time函数得到的时间类型也好,最终其实都是长整形的一个变量。两个这样的变量,就很明显可以做减法了。

做减法得到值是相差的秒数,这个秒数对86400(一天的秒数)取余,则得到相差数。如果对86400取模,还对3600秒、60秒取余,则得到相关的小时和分钟数。如果对86400取模,再对60取模,则得到相差的秒数。

原文地址:https://segmentfault.com/a/1190000016816083

猜你喜欢

转载自www.cnblogs.com/lalalagq/p/9964195.html