如何从另一个 DateTime 中减去 DateTime 对象并获取 +N 或 -N 中的分钟数

How To Subtract On DateTime Object From Another DateTime and Get The Minutes in +N or -N

我正在做一个考勤系统。我需要帮助找到迟到的人。区别只给我区别没有-N或+N

$ClockIn = "2019-08-29 06:45:00.000000";
$OpeningTime= "2019-08-29 07:00:00.000000";
$LateTimeDifferenceInMinutes = ($OpeningTime->diff($ClockIn))->i;
$LateTimeDifferenceInMinutes = 15; 

$ClockIn = "2019-08-29 07:01:00.000000";
$OpeningTime= "2019-08-29 07:00:00.000000";
$LateTimeDifferenceInMinutes = ($OpeningTime->diff($ClockIn))->i;
$LateTimeDifferenceInMinutes = 1;

我想得到肯定或否定的分钟数,以确保此人迟到

使用 new DateTime() 将字符串变量转换为日期。

$ClockIn = new DateTime("2019-08-29 07:07:00.000000");
$OpeningTime= new DateTime("2019-08-29 07:00:00.000000");
$negorpos =  $ClockIn->diff($OpeningTime)->format('%r');
$diff=  $ClockIn->diff($OpeningTime);

$mins = $negorpos . (($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i);
//output: -7

方法1,如果你想在几分钟内得到差异,你可以使用时间戳

  $timestamp1 = strtotime("2019-08-29 06:45:00.000000");
  $timestamp2 = strtotime("2019-08-29 07:00:00.000000");

  echo intval(($timestamp1  - $timestamp2)/60) . "m";

方法2,可以用invert取号,invert and check the demo

invert: Is 1 if the interval represents a negative time period and 0 otherwise. See DateInterval::format().

  $ClockIn = new DateTime("2019-08-29 06:45:00.000000");
  $OpeningTime= new DateTime("2019-08-29 07:00:00.000000");

  $diff= $OpeningTime->diff($ClockIn);
  var_dump($diff->format("%R%i minutes"));
  var_dump(($diff->invert ? "-" : "") . $diff->i);

,php manual note

It is worth noting, IMO, and it is implied in the docs but not explicitly stated, that the object on which diff is called is subtracted from the object that is passed to diff.

i.e. $now->diff($tomorrow) is positive.