Search code examples
phpstringdatetimetimedateinterval

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


I am making an attendance system. i need help in getting the late person. difference give me only difference no -N or +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;

i want to get the minutes in positive or negative that i make sure that the person is late


Solution

  • use new DateTime() to convert your string variable to date.

    $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