【问题标题】:PHP Date / Time ProblemPHP日期/时间问题
【发布时间】:2011-03-09 22:33:29
【问题描述】:

因此,我正在尝试计算以下日期的天数差异。其中一个有效,但另一个数字已关闭。应该是 3。

我可以使用ceil 函数,但我仍然不知道为什么以下内容不正确。

$checkOut = strtotime('2011-02-16'); $checkIn = strtotime('2011-02-11'); 回声 ($checkOut - $checkIn) / (60 * 60 * 24); // => 5 echo floor(($checkOut - $checkIn)/(60*60*24)); // => 5 $checkOut = strtotime('2011-03-14'); $checkIn = strtotime('2011-03-11'); 回声 ($checkOut - $checkIn) / (60 * 60 * 24); // => 2.958333333 echo floor(($checkOut - $checkIn)/(60*60*24)); // => 2

【问题讨论】:

  • 就是这样!谢谢!虽然 PHP 规范说 strtotime 返回自纪元以来的秒数,但我想情况并非如此。
  • 接缝在这里工作ideone.com/ai3jo,两者都输出 3
  • 当我做第二个块时,我得到 3,正如预期的那样
  • @James 它正在返回自纪元以来的秒数,但它将输入日期解释为处于某个时区(可能不是 UTC)
  • 啊,好点。不确定我们的生产系统使用的是什么 PHP 版本,但假设如果我指定 UTC,它可以工作,我会这样做。

标签: php date time strtotime


【解决方案1】:

为什么不用php面向对象的DateTime::diff

<?php
$datetime1 = new DateTime('2011-03-11');
$datetime2 = new DateTime('2011-03-14');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

【讨论】:

    【解决方案2】:

    您可能希望使用DateTime::diff() 来解决该问题。

    通过使用 floor(),您实际上得到了下一个较小的整数(去掉逗号后的所有内容)。

    【讨论】:

      【解决方案3】:

      所以问题是因为它跨越了夏令时。尽管 PHP 规范说 strtotime 返回纪元以来的秒数,但我想情况并非如此。

      【讨论】:

      • 嗯,当然它会返回自纪元以来的秒数。从/到 DST 的切换使一天缩短/延长了 3600 秒,因此在“自纪元以来的秒数”中缺少这 3600 秒。
      • 嗯...我不相信这是真的,即使根据我给出的定义。 en.wikipedia.org/wiki/Unix_time
      猜你喜欢
      • 2014-08-20
      • 2010-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多