使用m-d-Y格式时,如何找到2个日期(以天为单位)的差异?

时间:2013-05-07 09:41:59

标签: php date strtotime datediff

我需要这样的东西

$today = date("m-d-Y");
$otherdate = "05-03-2013";

//Some math here

//echo the difference between the two dates in days

我尝试过使用strtotime,但它没有正常工作,通常会说差异大约是15k天(显然不对)

任何帮助?

3 个答案:

答案 0 :(得分:1)

尝试DateTime的{​​{3}}方法:

$now  = new DateTime();
$then = DateTime::createFromFormat('m-d-Y', '05-03-2013');

$interval = $now->diff($then);

$days = $interval->format('%a days');

答案 1 :(得分:0)

尝试Y-m-d格式日期

$now = strtotime(date("Y-m-d")); // or your date as well
$otherdate = strtotime("2013-05-03");
$datediff = $now - $otherdate;
echo floor($datediff/(60*60*24)). "Days";

答案 2 :(得分:0)

PHP 5.3 +

$b_date1 = new DateTime($date);
$today1 = new DateTime($today);
$interval = date_diff($today1,$b_date1);

PHP版本小于5.2

function date_diff1($date1, $date2) { 
    $current = $date1; 
    $datetime2 = date_create($date2); 
    $count = 0; 
    while(date_create($current) < $datetime2){ 
        $current = gmdate("Y-m-d", strtotime("+1 day", strtotime($current))); 
        $count++; 
    } 
    return $count; 
}