PHP计算两个时间相差的年月时分秒
网络整理 - 08-10
PHP如何计算两个时间相差几年几月几时几分几秒呢?先将两个时间转化为时间戳,然后相减得到两个时间相差的秒数,最后进行一些算术就可以得到两个时间相差的年月日时分秒了,完整的代码如下:<?php
$time1 = "2008-6-15 11:49:59";//第一个时间
$time2 = "2007-5-5 12:53:28";//第二个时间
$t1 = strtotime($time1);
$t2 = strtotime($time2);
$t12 = abs($t1-$t2);
$start = 0;
$string = "两个时间相差:";
$y = floor($t12/(3600*24*360));
if($start || $y )
{
$start = 1;
$t12 -= $y*3600*24*360;
$string .= $y."年";
}
$m = floor($t12/(3600*24*31));
if($start || $m)
{
$start = 1;
$t12 -= $m*3600*24*31;
$string .= $m."月";
}
$d = floor($t12/(3600*24));
if($start || $d)
{
$start = 1;
$t12 -= $d*3600*24;
$string .= $d."天";
}
$h = floor($t12/(3600));
if($start || $h)
{
$start = 1;
$t12 -= $h*3600;
$string .= $h."时";
}
$s = floor($t12/(60));
if($start || $s)
{
$start = 1;
$t12 -= $s*60;
$string .= $s."分";
}
$string .= "{$t12}秒";
echo $string;
?>