PHP - 相互扣除两个时间戳,以分钟显示

时间:2016-01-25 10:47:01

标签: php mysql timestamp

我有一个mySQL数据库,用于存储健身房中人员的登记和结账时间。我已将签入和签出时间导入到我的PHP脚本中。现在我想从彼此中扣除两个时间戳 - 给我剩下的时间。我想在几分钟内显示它。

这是我的想法:

$checkOut = "2016-01-31 15:01:11";
$checkIn = "2011-01-31 15:32:35";
echo ($checkIn - $checkOut);

// I want this to display 31 minutes. 

我在StackOverflow上看过很多例子,但没有一个与我的描述相符,我无法对我找到的那些进行反向工程 - 因为他们使用time()函数 - 我猜这需要当前的时间。

3 个答案:

答案 0 :(得分:1)

$checkOut = "2016-01-31 15:01:11";
$checkIn = "2011-01-31 15:32:35";
 $time = (strtotime($checkIn) - strtotime($checkOut));
echo date('i',$time);

使用此代码

答案 1 :(得分:1)

您可以使用strtotime();

$checkOut = "2016-01-31 15:01:11"; // initial value
$checkIn = "2011-01-31 15:32:35"; // initial value

$checkOut_stamp = strtotime($checkOut); // Converting to unix timestamp
$checkIn_stamp = strtotime($checkIn);  // Converting to unix timestamp
echo date("i", ($checkIn - $checkOut)) . 'Minute(s)';

IMP注意:上述方法仅在分钟数低于59时才有效,否则小时数将四舍五入并且被丢弃。因此,如果您的要求显示的时间(以分钟为单位,可能超过59分钟eg. 144 minutes),那么您希望除以60,如下所示。

    $checkOut = "2016-01-31 15:01:11"; // initial value
    $checkIn = "2011-01-31 15:32:35"; // initial value

    $checkOut_stamp = strtotime($checkOut); // Converting to unix timestamp
    $checkIn_stamp = strtotime($checkIn);  // Converting to unix timestamp
    $seconds = $checkOut_stamp - $checkIn_stamp;
    if($seconds > 0){
      if($seconds > 60){
       $minutes = $seconds/60;
      } else {
       $minutes = 0;
      }
    } else {
      $minutes = 0;
    }

    echo  $minutes . ' Minute(s)';

答案 2 :(得分:0)

如果从数据库中获取此记录,则可以使用MySql函数TIMESTAMPDIFF简单地实现它,因为不需要在此处使用PHP函数

Select TIMESTAMPDIFF(MINUTE,checkIn,checkout) as tot_diff from your_table