首页 > 解决方案 > 在foreach循环内以小时为单位获取两个日期之间的差异

问题描述

我想要的是获得用户的开始日期和结束日期之间的差异。有开始日期和结束日期的用户有 3 个日期。并且当我尝试时,所有来自数据库的日期都无法获得所需的结果,即从日期列表中获取日期之间的差异,例如 2 天、3 天、4 天,并且没有显示错误。

我的代码

<?php 
    $eid = $_SESSION['eid'];
    $sql = "SELECT empid,ToDate,FromDate from tblleaves where empid=:eid";

    $query = $dbh->prepare($sql);
    $query->bindParam(':eid',$eid,PDO::PARAM_STR);
    $query->execute();

    $results = $query->fetchAll(PDO::FETCH_OBJ);

    if($query->rowCount() > 0) {
        foreach($results as $result)
        {  
            $diff = date_diff($result->ToDate, $result->FromDate);
            echo $diff->format("%h Hours");
            htmlentities($result->FromDate));
        }
    }
?>

数据库:

在此处输入图像描述

标签: php

解决方案


您在数据库中的日期格式是错误的,您必须先将其替换为/例如-str_replace('/', '-', $result->ToDate))

然后你必须将日期转换为正确的格式Y-m-d,之后你可以检查差异,这里是你的解决方案

$to = date('Y-m-d', strtotime(str_replace('/', '-', $result->ToDate)));
$from = date('Y-m-d', strtotime(str_replace('/', '-', $result->FromDate)));

$datediff = strtotime($to) - strtotime($from);

echo abs(round($datediff / (60 * 60 * 24)));

如果您想要小时数的差异,您可以尝试以下代码

$hourdiff = abs(round(($datediff)/3600, 1));

我希望这能帮到您


推荐阅读