0

I am retrieving records from a database which have separate date and time field and combining them into date time objects so that I can get the difference between start and finish date/time. I also want to calculate to total number of hours that have passed for the number of records returned.

My current code is like this

$temp_total = date_create("00:00");
while($row = mysqli_fetch_assoc($result))
{   
    $startDate = $row['StartDate'];
    $startTime = $row['StartTime'];
    $start = $startDate . " " . $startTime;
    $start = new DateTime($start);
    $finishDate = $row['FinishDate'];
    $finishTime = $row['FinishTime'];
    $finish = $finishDate . " " . $finishTime;
    $finish = new DateTime($finish);
    $duration = $start->diff($finish);

    $temp_total->add($duration);
}

This just ends up with the times wrapping around i.e. 8hr, 12hr and 12 hrs gives me a total of 8 hours which I assume is because I am missing the added day somewhere.

Am I going about this in the right way or is there a better way of doing it?

Al W
  • 43
  • 6
  • This works yes. Why did you choose to put date and time in a differt column tho? – Daan Aug 15 '16 at 14:01
  • I didnt choose to do it that way, it already was unfortunately – Al W Aug 15 '16 at 14:03
  • I think better would be to use timestamp here. `$start = strtotime($start)` and same with end, then `$diff = $end-$start`, then after cycle just divide for 3600. And yea thats a really strange to put time and date to different columns. – ineersa Aug 15 '16 at 14:04
  • Have you seen this? http://stackoverflow.com/questions/11556731/how-we-can-add-two-date-intervals-in-php – Don't Panic Aug 15 '16 at 14:15

0 Answers0