php 计算两个时间相差多少天

如题所述

有时可能会碰到这种需求,需要计算两个日期相隔多少天?
下面这个函数很好的解决了这个问题
<?php

/*
*
*函数功能:计算两个以YYYY-MM-DD为格式的日期,相差多少天(日)
*return int
*/

function getChaBetweenTwoDate($date1,$date2){
$Date_List_a1=explode("-",$date1);
$Date_List_a2=explode("-",$date2);
$d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]);
$d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]);
$Days=round(($d1-$d2)/3600/24);
return $Days;
}

使用方法如下:
echo getChaBetweenTwoDate('2012-11-20','1949-10-16');

以上代码执行结果将显示为:
23046
意思即这两个日期相差 23046 天。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-02-08
先转成时间戳 用strtotime 然后差值 除以 60*60*24