PHP日期差计算



$departure2014-06-02$date2014-06-01。事实上,我在沙盒中运行了这个,结果是正确的。然而,这是我在页面上的输出:2014-06-02 date: 2014-06-01 g: 16222

这是我的代码:

$days = 0;
$departure = strtotime($r['departure']);
echo $r['departure'];
echo " date: ".$date;
$datediff = abs(strtotime($date) - strtotime($departure));
$days = floor($datediff/(60*60*24));
echo " g: ".$days++;

所以天应该是2,但它是16222。这是怎么回事?

看起来您要用strtotime转换$r["department"]两次。这太多了。尝试只进行一次转换的代码,它应该会更好地工作。

我通常使用Date类,以下是可能对您有所帮助的函数(最后我添加了一个示例(:

<?php
function sqlInt($date) {
    return mktime($date['hour'], $date['minutes'], 0, $date['month'], $date['day'], $date['year']);
}
function differenceInt($dateStart, $dateEnd) {
    $start = sqlInt($dateStart);
    $end = sqlInt($dateEnd);
    return $end - $start;
}
function difference($dateStart, $dateEnd) {
    $difference = differenceInt($dateStart, $dateEnd);
    $result = array();
    $result['hours'] = $difference/3600;
    $result['minutes'] = $difference/60;
    $result['days'] = $difference/86400;
    return $result;
}
$dateStart = array('hour'=>'0', 'minutes'=>'0', 'month'=>'6', 'day'=>'1', 'year'=>'2014');
$dateEnd = array('hour'=>'0', 'minutes'=>'0', 'month'=>'6', 'day'=>'2', 'year'=>'2014');
echo '<pre>';
print_r(difference($dateStart, $dateEnd));
echo '</pre>';
?>

它的简单u需要使用DateTime类

$date1 = new DateTime($firstdate);
$date1ready = $date1->format('Y-m-d');
$date2 = new DateTime($seconddate);
$date2ready = $date1->format('Y-m-d');
$difff = $date2->diff($date1);
$days = $difff->d;

相关内容

  • 没有找到相关文章

最新更新