简体   繁体   English

比较两个日期结果0

[英]Comparing two dates results 0

so i'm currently making a small php application and I need to compare two dates to get the number of days between them. 所以我目前正在制作一个小型php应用程序,我需要比较两个日期以获取它们之间的天数。 I sadly can't use datediff() since the php version is 5.2. 可悲的是我不能使用datediff(),因为php版本是5.2。

I've search how to do and I found a lot of answers but I always have the same problem. 我已经搜索了怎么做,发现了很多答案,但是我总是遇到同样的问题。 When I make the difference between my dates, I always got 0 as a result. 当我在日期之间进行区分时,结果总是为0。

function date_diff($dateFrom, $dateTo) {
    echo $dateFrom->format('d-m-Y') . " : " . $dateTo->format('d-m-Y') . '<br/>';
    $diff = abs($dateTo-$dateFrom);

    return sprintf
    (
        "%d Days, %d Hours, %d Mins, %d Seconds",
        intval( $diff / 86400 ),
        intval( ( $diff % 86400 ) / 3600),
        intval( ( $diff / 60 ) % 60 ),
        intval( $diff % 60 )
    );
}

I currently use this function and the parameters are here : 我目前正在使用此功能,参数在这里:

    while ($donnees = mysqli_fetch_array($res))
        $date = new DateTime($donnees['Date']);


    $date = date_create($date->format("Y-m-d"));
    $today = new DateTime();

    echo $utilDate->date_diff($date, $today);

My $date and $today variables are not empty, so I don't understand why this code doesn't work. 我的$ date和$ today变量不是空的,所以我不明白为什么这段代码不起作用。 Does anyone have an idea? 有人有主意吗?

I think $dateTo and $dateFrom are objects and you are doing a substraction on them in $diff = abs($dateTo-$dateFrom); 我认为$ dateTo和$ dateFrom是对象,并且您在$diff = abs($dateTo-$dateFrom);

Try $diff = abs($dateTo->getTimestamp()-$dateFrom->getTimestamp()); 试试$diff = abs($dateTo->getTimestamp()-$dateFrom->getTimestamp());

You want to use the diff operator: 您要使用diff运算符:

function date_diff($dateFrom, $dateTo) {
    echo $dateFrom->format('d-m-Y') . " : " . $dateTo->format('d-m-Y') . '<br/>';
    $diff = $dateNow->diff($dateTo);

    $day = $diff->format('%d');
    $hour = $diff->format('%h');
    $min = $diff->format('%i');
    $seconds = $diff->format('%s');

    return /*string involving above formats*/;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM