【问题标题】:math operations on time variables时间变量的数学运算
【发布时间】:2011-11-30 09:16:22
【问题描述】:

如果我有 2 个时间变量:

    a = 00:00:12 and b = 00:00:05

我如何将它们加在一起制作:

    c = 00:00:17 ?

然后我需要将它们分成一个平均值, 但我坚持添加部分。

我以这种格式从数据库中获取数据,当我尝试一个简单的:

    c=a+b;

我明白了:

    00

如何对时间变量进行简单的数学运算?

【问题讨论】:

    标签: php mysql math time


    【解决方案1】:

    或者你直接往前走;-)

    <?php
    $a = "00:00:12";
    $b = "00:00:05";
    
    function addTime($timeA, $timeB) {
        $timeAcomponents = explode(":", $timeA);
        $timeBcomponents = explode(":", $timeB);
    
        $timeAinSeconds = $timeAcomponents[0]*60*60 + $timeAcomponents[1]*60 + $timeAcomponents[2];
        $timeBinSeconds = $timeBcomponents[0]*60*60 + $timeBcomponents[1]*60 + $timeBcomponents[2];
    
        $timeABinSeconds = $timeAinSeconds + $timeBinSeconds;
    
        $timeABsec = $timeABinSeconds % 60;
        $timeABmin = (($timeABinSeconds - $timeABsec) / 60) % 60;
        $timeABh = ($timeABinSeconds - $timeABsec - $timeABmin*60) / 60 / 60;
    
        return str_pad((int) $timeABh,2,"0",STR_PAD_LEFT).":"
              .str_pad((int) $timeABmin,2,"0",STR_PAD_LEFT).":"
              .str_pad((int) $timeABsec,2,"0",STR_PAD_LEFT);
    }
    
    echo "Adding time variables:\n";
    echo "$a + $b = ".addTime($a, $b);
    ?>
    

    【讨论】:

    • 不客气,但请考虑这根本不是一种好的编程风格;-) 这是直接的方式,不推荐。 N.B.、Devart 或 Ondrejs 的答案更优雅。
    【解决方案2】:

    只需对所有操作使用mktime,然后在输出日期时将其转换回可读格式(使用date):

    $a = mktime(0, 0, 12);
    $b = mktime(0, 0, 5);
    
    echo date('G:i:s', $a + $b);
    echo date('G:i:s', ($a + $b) / 2);
    

    【讨论】:

      【解决方案3】:
      $date['first'] = DateTime::createFromFormat('H:i:s', "00:00:12");
      $date['second'] = DateTime::createFromFormat('H:i:s', "00:00:05");
      
      $interval = new DateInterval('PT'. $date['second']->format('s') .'S');
      
      $date['first']->add($interval);
      
      echo $date['first']->format('s'); // echoes 17
      

      【讨论】:

        【解决方案4】:

        在 MySQL 中你可以这样做 -

        SET @a = '00:00:12';
        SET @b = '00:00:05';
        
        SET @a_sec = TIME_TO_SEC(@a);
        SET @b_sec = TIME_TO_SEC(@b);
        
        SET @c_sec = @a_sec + @b_sec;
        
        SELECT SEC_TO_TIME(@c_sec);
        +---------------------+
        | SEC_TO_TIME(@c_sec) |
        +---------------------+
        | 00:00:17            |
        +---------------------+
        

        【讨论】:

          猜你喜欢
          • 2018-09-26
          • 1970-01-01
          • 1970-01-01
          • 2011-08-15
          • 1970-01-01
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多