gpt4 book ai didi

PHP DateTime::Diff "steals"一天

转载 作者:可可西里 更新时间:2023-11-01 00:08:55 24 4
gpt4 key购买 nike

我想计算两天之间的日期差异。问题是当我计算天数时,计算中缺少一天(当天)。

假设 date1 是 20-12-2014,date2 是 21-12-2014。DateTime::Diff 使用这两个日期的结果是 0(我想是 1,而不是零)

我是不是漏掉了什么不好的东西,或者 DateTime::Diff 像我上面解释的那样计算日期差异?

这是我正在使用的代码(我想以天为单位显示日期差异):

      $currentDay = new DateTime();
$listDay = new DateTime($results["date"]);//from mysql database (output is like 21-12-2014
$interval = $currentDay->diff($listDay);
$daysLeft=(int)$interval->format("%r%a");

最佳答案

就像@Matt 在评论中已经说过的那样,您不仅要比较日期,还要比较日期和时间,在 $currentDay 变量中,您将时间设置为当前时间,在 中设置时间$listDay 设置为 00:00:00。如果转储这 2 个变量,例如 print_r($currentDay);print_r($listDay);,你可以很快看到。

解决方案是,创建 $currentDay DateTime 对象,时间设置为 00:00:00,这可以很容易地用 today 关键词:

$currentDay = new DateTime('today');
$listDay = new DateTime($results['date']);
$interval = $currentDay->diff($listDay);
echo $interval->format('%r%a');

demo

关于PHP DateTime::Diff "steals"一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27465540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com