【问题标题】:Calculate time difference with formatted time使用格式化时间计​​算时差
【发布时间】:2018-07-15 03:03:42
【问题描述】:

我有两个时间:开始时间和持续时间。我想从开始时间中减去持续时间。我从 mysql 数据库读取并且已经格式化的时间。我的代码:

$start= $row["start"]; //output is for e.g. 08:00:00
$dur = $row["duration"]; //output is for e.g. 01:00:00

$sub = $start - $dur; 
// I want the output to be 07:00:00
// the result now is 7 and I got an error (non well formed numeric value)

有人可以帮助我吗?

【问题讨论】:

  • 你用谷歌搜索了吗? php.net/manual/en/function.date-diff.php
  • 是的,我已经试过了。总是收到此错误:DateInterval 无法转换为字符串。我想这是因为我的时间已经在 mysql db 中格式化了

标签: php mysql datetime mysqli


【解决方案1】:

或者你也可以这样实现

$date = "1970-01-01";
$start = $date." ".$row["start"];
$dur = $date ." ".$row["duration"];
$date1=date_create($start);
$date2=date_create($dur);
$diff=date_diff($date1,$date2);
echo $diff->format("%H:%I:%S");

【讨论】:

    【解决方案2】:
    $start= "08:00:00";
    $dur = "01:00:00";
    
    $diff = differenceInHours($start, $dur);
    
    echo convertTime($diff);
    
    
    function differenceInHours($startdate,$enddate){
        $starttimestamp = strtotime($startdate);
        $endtimestamp = strtotime($enddate);
        $difference = abs($endtimestamp - $starttimestamp)/3600;
        return $difference;
    }
    
    function convertTime($dec)
    {
        // start by converting to seconds
        $seconds = ($dec * 3600);
        // we're given hours, so let's get those the easy way
        $hours = floor($dec);
        // since we've "calculated" hours, let's remove them from the seconds variable
        $seconds -= $hours * 3600;
        // calculate minutes left
        $minutes = floor($seconds / 60);
        // remove those from seconds as well
        $seconds -= $minutes * 60;
        // return the time formatted HH:MM:SS
        return lz($hours).":".lz($minutes).":".lz($seconds);
    }
    
    // lz = leading zero
    function lz($num)
    {
        return (strlen($num) < 2) ? "0{$num}" : $num;
    }
    

    【讨论】:

    • 感谢您的回答,但仍然是相同的错误和相同的输出:“遇到格式不正确的数值”,输出用于例如7
    • 你的 PHP 版本是多少?
    • 我的PHP版本是7.1.1
    【解决方案3】:

    您应该始终以适当的格式将日期保存在数据库中。而不是作为“已经格式化”的值。除非在非常特殊的情况下。

    无论如何,要解决您的问题,您可以这样做

    $start = new DateTime('08:00:00');
    $duration = new DateTime('01:00:00');
    
    $interval = date_diff($start, $duration);
    
    echo $interval->format('%H:%I:%S'); //ouput will be 07:00:00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      相关资源
      最近更新 更多