我得到两个日期$date1=2020-07-16 03:50:32$date2=2017-01-25 09:43:53
我想知道这两个日期的区别。差值计算小时到24小时,然后是天加小时。例如2天5小时。
我试过的代码是这个
$createddate = date("d-m-Y H:i:s", strtotime($application['created_at']));
$approvedisapprovedate = date("d-m-Y H:i:s", strtotime($application['approved_at']));
$created = strtotime($createddate);
$approvedisapprove = strtotime($approvedisapprovedate);
$diff = $approvedisapprove - $created;
$days = floor($diff / (60 * 60 * 24));
$hours = round(($diff - $days * 60 * 60 * 24) / (60 * 60));
但它不起作用。任何人都提出了解决方案。
您可以使用碳。碳可以非常有效地简化日期操作,不仅适用于此任务,还适用于许多其他相关日期。
安装碳
{
"require": {
"nesbot/carbon": "^1.22"
}
}
用法
$date->diffForHumans();
或
$date->diffInDays();
在您的情况下,您可以尝试以下代码-
$createddate = Carbon::parse($application['created_at']);
$approvedisapprovedate = Carbon::parse($application['approved_at']);
//here is carbon magic
$createddate->diffInDays($approvedisapprovedate); //This will give you diff in number of days.
$createddate->diffForHumans($approvedisapprovedate); //This will give you diff which is readable by human. ex- 1 day 2 hours
你可以参考Carbon。
希望这对你有帮助。
我建议您使用php的DateInterval::format函数像这样:
$createddate = new DateTime('12-07-2020 12:10:01');
$approvedisapprovedate = new DateTime('16-07-2020 13:15:40');
$interval = $approvedisapprovedate->diff($createddate);
echo $interval->format('%a days %h hours %i minutes')."n";
它回到这个:
4天1小时5分钟
我不知道日期的格式$application['created_at']和$application['approved_at'][strong>,但我只是把它放在那里:
$createddate = new DateTime($application['created_at']);
$approvedisapprovedate = new DateTime($application['approved_at']);
$interval = $approvedisapprovedate->diff($createddate);
echo $interval->format('%a days %h hours %i minutes')."n";
voici le lien de日期间隔::format:https://www.php.net/manual/fr/dateinterval.format.php