php - 在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));
}
}
?>
数据库:
解决方案
您在数据库中的日期格式是错误的,您必须先将其替换为/
例如-
。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));
我希望这能帮到您
推荐阅读
- firebase - 错误:projects:list 不是 Firebase 命令
- android - 缩放图像在手机上无法正常工作
- java - 使用 KeyListener 加载和更新 BufferedImage 组件
- c - 我的 C 程序给我的输出与我在这里看到的用 Java 编写的代码不同。(目的相同)
- javascript - 异步等待获取未定义。怎么处理?
- python - 使用 Pandas 加载具有完整路径的 .csv 文件时出现问题
- ruby - 自定义 Sinatra 路线
- c# - GroupBy之后,将一个组中的多条记录压缩为一条
- javascript - 如何从 JavaScript 对象中获取属性同时删除它
- python - 我的函数不断从整数列表中跳过负值