如何在数据库中保存间隔时间

时间:2019-07-02 03:02:31

标签: php mysql

如何在数据库中保存间隔时间。我需要选择哪种类型:stringtimedate

我只是在MySQL中获取最后一个数据(打开时间),只需要保存关闭时的持续时间即可。

// error in the line below
$sendresult = $interval->format('%y yr %d dy %H hr %i mn %s sc');

$host = "localhost";
  $user = "…";
  $pass = "…";
  $db = "…";
  $con = mysqli_connect($host, $user, $pass, $db);
  if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

$username="sam";
$id="01";
$date = date('Y-m-d H:i:s');
$statusdevide="off";

$result = mysqli_query($con,"SELECT *  FROM SPA02 ORDER BY Date DESC LIMIT 1");
$printdata=mysqli_fetch_row($result);
$datalpas=new DateTime($printdata[2]);
$interval = $datalpas->diff($datetime2);
$sendresult=$interval->format('%y yr %d dy %H hr %i mn %s sc');//00 years 0 months 0 days 08 hours 0 minutes 0 seconds
$sql = "INSERT INTO SPA02 (User, Id, Date,Status,Duration)
VALUES ('$username', '$id', '$date','$statusdevide','$sendresult')";

if (mysqli_query($con, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($con);
}

mysqli_close($con);

我期望的是将持续时间保存在数据库中,相反,我得到了:

  1. Warning: DateTime::diff() expects parameter 1 to be DateTimeInterface,
  2. PHP Fatal error:  Uncaught Error: Call to a member function format() on boolean

1 个答案:

答案 0 :(得分:0)

https://stackoverflow.com/a/43647408/11169816

好吧,谢谢。

$result = mysqli_query($con,"SELECT *  FROM SPA02 ORDER BY Date DESC LIMIT 1");
$printdata=mysqli_fetch_row($result);
$datalpas=new DateTime($printdata[2]);

$datetime11 = new DateTime($date);
$datetime22 = new DateTime($printdata[2]);  // change the millenium to see output difference
$diff = $datetime11->diff($datetime22);

$details=array_intersect_key((array)$diff,array_flip(['y','m','d','h','i','s']));



echo "\n";

array_map(function($v,$k)
    use(&$r)
    {
        $r.=($k=='y'?str_pad($v,4,"0",STR_PAD_LEFT):str_pad($v,2,"0",STR_PAD_LEFT));
        if($k=='y' || $k=='m'){$r.="-";}
        elseif($k=='d'){$r.=" ";}
        elseif($k=='h' || $k=='i'){$r.=":";}
    },$details,array_keys($details)
);



$sql = "INSERT INTO SPA02 (User, Id, Date,Status,Duration)
VALUES ('$username', '$id', '$date','$statusdevide','$r')";

if (mysqli_query($con, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($con);
}