I am new here. Please dont judge me.
This is my script which is CSV spreadsheet with people which race with start time and end time. i want to get the differences in the minutes . I get Output : 10:45 – 11:45 = 21 , i know i have to convert that to a time, but i don’t know how. Im newbie .
Thank you in advance 🙂
<?php const Start = 2; const Finish = 3; $startTime = 0; $endTime = 0; $row = 1; if (($handle = fopen("racing.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $startTime = $data[Start]; $endTime = $data[Finish]; } fclose($handle); echo "Difference ".$startTime."+".$endTime." = ".($startTime + $endTime); } ?>
Advertisement
Answer
$startTime = $data[Start]; $endTime = $data[Finish]; $startParts = explode(":", $startTime); $endParts = explode(":", $endTime); $startMinute = (int)$startParts[1]; $startHour = (int)$startParts[0]; $endMinute = (int)$endParts[1]; $endHour = (int)$endParts[0]; $differenceHour = ($endHour - $startHour); $differenceMinute = ($endMinute - $startMinute); $differenceHour -= (($differenceMinute < 0) ? 1 : 0); if ($differenceMinute < 0) $differenceMinute += 60; $difference = $differenceHour * 60 + $differenceMinute;
Explanation:
- we get
$startTime
and$endTime
as composite raw texts, such as 09:23 - we divide them using
explode
, the 0th elements will be hours, the 1th elements will be minutes - we store the parts accordingly into
$startMinute
,$startHour
,$endMinute
,$endHour
- we compute the difference of hours and store the result into
$differenceHour
- we compute the difference of minutes and store the result into
$differenceMinute
- if
$differenceMinute
is negative, that means that in terms of minute start time has a higher value, we need to subtract this from the hours result - if
$differenceMinute
was negative, then we need to compute the invert subtraction, that is, if we had 21 – 37, then we will end up with 42, so, 21 – 37 = -18 and if we add 60, we end up with 42 - finally we compute the result of the results and store it into
$difference
, which is the result that you need