PHP计算时间差的示例代码

发布时间:2020-01-30编辑:脚本学堂
分享一例php计算任意时间与当前时间差的代码,php时间计算的方法,有需要的朋友参考下。

例子,php计算时间差的代码。

代码:
 

复制代码 代码示例:
<?
#作者:仙乐
#功能:获得任意时间与当前时间的时间差
function QueryDays($datestr){
#格式化时间
    $da=preg_split("/(-| |:)/i",$datestr);
    $nowyear=date("Y");
    $nowmon=date("n");
    $nowday=date("d");
    $nowtimes=mktime(0,0,0,$nowmon,$nowday,$nowyear);
    $pdtimes= mktime(0,0,0,$nowmon,$nowday,$nowyear-1);
    $bjtimes= mktime(0,0,0,$da[1],$da[2],$da[0]);
#判断所给出的时间是不是在一年内
    if ($bjtimes>=$pdtimes and $bjtimes<=$nowtimes){
        return (floor(strftime("%j",mktime(0,0,0,$nowmon,$nowday,$nowyear)-mktime($da[3],$da[4],$da[5],$da[1],$da[2],$da[0]))));
    }else{
        $loop=$nowyear-$da[0];
        $totaldays=(floor(strftime("%j",mktime(0,0,0,$nowmon,$nowday,$nowyear)-mktime(0,0,0,1,1,$nowyear))));
        for($i=1;$i<=$loop;$i++){
            for($j=12;$j>=1;$j--){
                if ($da[0]==$nowyear-$i and $da[1]==$j){
                    $days=MonDays($nowyear-$i,$j);
                    return $totaldays+=$days-$da[2];
                    break;
                }else{
                    $days=MonDays($nowyear-$i,$j);
                    $totaldays+=$days;
                }//end else
             }//end for
        }//end for
    }//end else
}//end function
#取得月分的天数
function MonDays($year,$month){
    switch ($month){
        case "1":
        case "3":
        case "5":
        case "7":
        case "8":
        case "10":
        case "12": $days=31;break;
        case "4":
        case "6":
        case "9":
        case "11": $days=30;break;
        case "2":
            if (checkdate($month,29,$year)){
                $days=29;
            }else{
                $days=28;
            }//end else
        break;
    }//end switch
    return $days;
}//end function
$datestr="2002-1-14 9:47:20";
echo QueryDays($datestr);
?>