【问题标题】:Difference between two time stamps in PHPPHP中两个时间戳之间的区别
【发布时间】:2015-05-25 02:09:03
【问题描述】:

在我看来,这应该回显 11 小时,但它返回 12;我错过了什么?

$start_time = "06:00";
$end_time = "17:00";
$LOD = date("H:i", ((strtotime($end_time) - strtotime($start_time))));
echo  "Length of day: " . $LOD . " hours";

更新:在 MAMP 环境中在我的 MBPro 上运行;系统时间设置为 24 小时。

【问题讨论】:

标签: php time mamp strtotime maxlength


【解决方案1】:

问题出在这里:

date_default_timezone_set('Asia/Singapore');
echo date('r', strtotime('06:00')); // Mon, 25 May 2015 06:00:00 +0800
date_default_timezone_set('America/Denver');
echo date('r', strtotime('06:00')); // Sun, 24 May 2015 06:00:00 -0600

注意到更改时区后日期如何偏移了一天?这是因为您提供给strtotime() 的日期是相对日期,因此您需要将其“接地”到一天的开始:

echo date('H:i', strtotime('17:00') - strtotime('06:00') + strtotime('00:00'));

或者,使用DateTime

$t1 = new DateTime('06:00');
$t2 = new DateTime('17:00');
echo $t2->diff($t1)->format('%H:%I');

【讨论】:

  • @Dan 不客气;我个人更喜欢使用 DateTime 来避免过多考虑时间戳 ;-)
  • 总是在球上@Ja͢ck,很好的答案!
【解决方案2】:

以这种方式使用date 没有任何意义。

如果你想要一个最小的感觉,那么你应该添加strtotime("00:00")作为你的初始时间。

(end - start) + init

【讨论】:

    【解决方案3】:

    因为它会变成你本地服务器的php时间。

    试试这个

    <?php
    
        $start_time = "06:30";
        $end_time = "17:50";
        $default_time = "00:00";
    
    
        $LOD = date("H:i", (strtotime($default_time)+(strtotime($end_time) - strtotime($start_time))));
        echo  "Length of day: " . $LOD . " hours";
    
        echo "<br>";
    
        $diff = strtotime($end_time) - strtotime($start_time);
        $hour = floor($diff / 3600);
        $minute = ($diff % 3600) / 60;
        echo "Length of day: " . $hour . ":" . $minute . " hours";
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-18
      • 2014-04-14
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 2012-02-29
      • 2021-09-01
      相关资源
      最近更新 更多