Thijmen
Thijmen

Reputation: 127

Calculate total hours, best solution?

I am making a table with entries, which contains a checkin, checkout and description. Both checkin and checkout are datetime fields.

I want to calculate the total amount of time worked on a project. This is my calculation between 1 checkout and a checkin:

{? $checkin = new DateTime($hour->checkin) ?}
{? $checkout = new DateTime($hour->checkout) ?}
@if($hour->checkout == '0000-00-00 00:00:00')
    {? $checkout = new DateTime() ?}
@endif
{? $diff = $checkout->diff($checkin) ?}
{? $hours = $diff->format('%H:%I') ?}

Now, I calculate the total amount of seconds by this:

$totaltime += strtotime("January 1, 1970 " . $hours . ":00")

And then after everything has been displayed, I calculate the amount of HOURS by this:

public static function format_time($seconds,$separator=':', $format = "%02d%s%02d") // t = seconds, f = separator 
    {
        return sprintf($format, floor($seconds/3600), $separator, ($seconds/60)%60, $separator, $seconds%60);
    }

Yet, when I do:-

strtotime("January 1, 1970 00:40:00")

I get a negative int. What am I doing wrong?

Upvotes: 0

Views: 362

Answers (1)

alexP
alexP

Reputation: 3765

<?php
$checkin[0] = "2013-03-09 10:00:01";
$checkout[0] = "2013-03-12 10:55:15";

$checkin[1] = "2013-03-15 10:00:01";
$checkout[1] = "2013-03-15 10:55:15";

$checkin[2] = "2013-04-09 10:00:01";
$checkout[2] = "2013-04-15 10:55:15";

$diffSeconds = 0;
for($i = 0; $i < count($checkin)-1; $i++){
  $diffSeconds += strtotime($checkout[$i]) - strtotime($checkin[$i]);
}
$hours = floor($diffSeconds/3600);
echo $hours.' hours';
?>

Upvotes: 1

Related Questions