PHP DateDiff 问题

发布于 2024-10-26 01:20:47 字数 552 浏览 1 评论 0原文

使用下面的 PHP 代码,我希望得到“2”作为我的输出。但我得到“1”。

有谁知道这是为什么?

$returndate = preg_replace('#(\d+)/(\d+)/(\d+)#', '$3-$2-$1', '2011-03-28');
$departdate = preg_replace('#(\d+)/(\d+)/(\d+)#', '$3-$2-$1', '2011-03-26'); 

$diff = abs(strtotime($returndate) - strtotime($departdate));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

echo $days; // expecting 2, but get 1

非常感谢您的帮助。

Using the PHP code below, I would expect to get '2' as my output. But I get '1'.

Does anyone know why this is?

$returndate = preg_replace('#(\d+)/(\d+)/(\d+)#', '$3-$2-$1', '2011-03-28');
$departdate = preg_replace('#(\d+)/(\d+)/(\d+)#', '$3-$2-$1', '2011-03-26'); 

$diff = abs(strtotime($returndate) - strtotime($departdate));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

echo $days; // expecting 2, but get 1

Many thanks for any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

人海汹涌 2024-11-02 01:20:47

如此多的计算...我认为这是您遇到的舍入问题,舍入所有时间测量...这是您正在做的事情的更简单的外观:

function dateDiff($start, $end) {
  $start_ts = strtotime($start);
  $end_ts = strtotime($end);
  $diff = $end_ts - $start_ts;
  return round($diff / 86400);
}

So much calculations... I assume its a rounding issue you have, rounding all the time measurements... here is a simpler look on what you are doing:

function dateDiff($start, $end) {
  $start_ts = strtotime($start);
  $end_ts = strtotime($end);
  $diff = $end_ts - $start_ts;
  return round($diff / 86400);
}
忆梦 2024-11-02 01:20:47
$d1 = new DateTime('2011-03-28');
$d2 = new DateTime('2011-03-26');

echo $d1->diff($d2)->d;

输出:2

$d1 = new DateTime('2011-03-28');
$d2 = new DateTime('2011-03-26');

echo $d1->diff($d2)->d;

Output: 2

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文