【问题标题】:Convert Digit Time to seconds [duplicate]将数字时间转换为秒 [重复]
【发布时间】:2017-05-19 17:19:42
【问题描述】:

如何将数字时间转换为秒?

我需要比较时间,所以我认为将数字时间转换为秒并稍后比较秒会更容易。

例如:

00:00:33
00:01:33
02:01:33

【问题讨论】:

  • “数字时间”是什么意思?
  • @Panda - 该页面上的解决方案虽然紧凑,但由于第一个 strtotime() 时间与第二个 strtotime() 时间略有不同,因此会出现不准确之处,因为它是按顺序处理的。在不优先考虑精度并且服务器负载最小的大多数情况下,它是很好的。
  • 很多答案,但没有人质疑为什么你想这样做。时间字符串已经具有可比性。相等和比较运算符在应用于字符串本身时已经按预期工作。

标签: php time digit date-conversion


【解决方案1】:

如果您要从该格式中寻找精确的秒数,您可以编写自定义解析器。

这样的事情应该可以解决问题:

echo hhmmss2seconds("18:24:35");

function hhmmss2seconds($time) {
    $digits = explode(":", $time);
    $seconds = 0;
    $seconds = $seconds + intval($digits[0]) * 3600; // hours
    $seconds = $seconds + intval($digits[1]) * 60; // minutes
    $seconds = $seconds + intval($digits[2]); // seconds    
    return $seconds;
}

【讨论】:

    【解决方案2】:

    您想使用strtotime()。这会将“数字时间”转换为 Unix 时间。

    $time_in_seconds = strtotime('00:00:33');
    

    【讨论】:

    • 如果我这样做很奇怪 $test = strtotime(00:00:33);回声 $test 。 '
      ';我得到一个意想不到的“:”
    • 嗯我现在没有收到错误,但它返回给我:1483570833
    • strtotime()的参数需要是字符串所以像这样:echo $test = strtotime("00:00:33");
    • 我修改了它,所以它被封装在引号中,但是 strtotime 的结果是不正确的。 proof it is not valid
    【解决方案3】:

    试试这个:

    echo strtotime("1970-01-01 00:00:11  UTC");
    

    【讨论】:

      【解决方案4】:

      试试这个它的工作原理

       <?php
          function time_to_seconds($time) { 
              list($h, $m, $s) = explode(':', $time); 
              return ($h * 3600) + ($m * 60) + $s; 
          }
          echo time_to_seconds("00:00:33");
          echo time_to_seconds("00:01:33");
          echo time_to_seconds("02:01:33");
      
          ?>
      

      谢谢你..

      【讨论】:

        猜你喜欢
        • 2019-07-04
        • 2014-01-29
        • 1970-01-01
        • 1970-01-01
        • 2014-10-16
        • 2012-08-29
        • 2013-08-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多