简体   繁体   中英

How to embed numbers values in a Date function in php then get difference?

I have a file in which i have to calculate the total hours of the time spent. But the problem is that the data i am receiving is broken into Hours and Minutes. I am converting it to the date() function and then find the difference with PHP built-in time_diff() function. But not succeeded yet.. Kindly help.... Here is my Data i am Fetching:

$HoursIn = $ls[$j][2];               // Punch-In Hours (e.g: 09)
$MinutesIn = $ls[$j][3];            // Punch-In Minutes (e.g: 38)
$TimeIn = $HoursIn.":".$MinutesIn; // Punch-In Total Time (e.g: 09:38)

$HoursOut = $ls[$j][4];                 // Punch Out Hours (e.g: 17)
$MinutesOut = $ls[$j][5];              // Punch Out Minutes (e.g: 44)
$TimeOut = $HoursOut.":".$MinutesOut; // Punch-Out Total Time (e.g: 17:44)

I have tried this:

$HoursIn = 09;               // Punch-In Hours (e.g: 09)
$HoursIn->format('%h');
$MinutesIn = 38;           // Punch-In Minutes (e.g: 38)
$MinutesIn->format('%i');
$TimeIn = $HoursIn.":".$MinutesIn; // Punch-In Total Time (e.g: 09:38)

$HoursOut = 17;                 // Punch Out Hours (e.g: 17)
$HoursOut->format('%h');
$MinutesOut = 44;              // Punch Out Minutes (e.g: 44)
$MinutesOut->format('%i');
$TimeOut = $HoursOut.":".$MinutesOut;

echo $interval = $TimeOut->diff($TimeIn);

But getting fatal Error...

Here you are my solution. The result for a sample is 1 hour and 3 mins. Hope it is clear but if any questions - ask me:

<?php
$in_time=sprintf("%04u-%02u-%02u %02u:%02u:02u",2015,5,6,12,5,0); // Values : Year Month Day hour min sec
$out_time=sprintf("%04u-%02u-%02u %02u:%02u:02u",2015,5,6,17,8,0); // Values : Year Month Day hour min sec
$TimeIn = new DateTime($in_time);
$TimeOut = new DateTime($out_time);

$interval = $TimeIn->diff($TimeOut);
echo $interval->format('%h:%i');
?>

@MarkBaker I have done this with your help! Thanks! I got the result like this:

$HoursIn = $ls[$j][2];         // Punch-In Hours
$MinutesIn = $ls[$j][3];      // Punch-In Minutes
$timein = gmdate('H:i:s', $HoursIn*60*60+$MinutesIn*60);

$HoursOut = $ls[$j][4];        // PunchOut Hours
$MinutesOut = $ls[$j][5];     // PunchOut Minutes
$timeout = gmdate('H:i:s', $HoursOut*60*60+$MinutesOut*60);

$time1 = new DateTime($timein);
$time2 = new DateTime($timeout);
$interval = $time1->diff($time2);           
$interval->format('%H:%i');

But Now I want to put a condition but the condition is not working: (I want to make $interval= 00:00 but this if condition is not working...)

if($timeout == "00:00:00") {$interval->format('%0:%0');}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM