0

I am trying to create a timesheet page where an employee can clock in and clock out. After they clock out, their total hours are calculated, hence, time2 (clock out) minus time1 (clock in). I used a set time here because I just want to know how to do the difference itself then I can figure out how to do the rest (everything else works except the total). I provided my code and the results. If you can solve the problem with the hours, I would appreciate it if you post the code and the results. Someone has suggested that I use abs() in line 54 but it still did not work. Thank you for your time.

$time1 = strtotime('09:10:04');
$time2 = strtotime('12:16:06');
$diff = $time2 - $time1;
echo "Start Time: ".date('h:i:s', $time1)."<br>";
echo "End Time: ".date('h:i:s', $time2)."<br>";
echo "Total hours: " . date('h:i:s', $diff);

Start Time: 09:10:04

End Time: 12:16:06

Total hours: 10:06:02

user3666355
  • 83
  • 3
  • 12

2 Answers2

0

I like DateTime for this

 $time1 = new DateTime('09:10:04');
 $time2 = new DateTime('12:16:06');
 $diff = $time1->diff($time2);
 echo $diff->format('%h hours');
Machavity
  • 30,841
  • 27
  • 92
  • 100
0

I think, your problem happening, since you live in timezone +7. when you extract times by strtotime(), system turn both times to UTC. when you subtract t2-t1, any timezone shift goes to zero.

But, when you print result, date() adds offset to your local timezone, and printed +7 hours.

For preserve this adding, just write once in the program beginning:

date_default_timezone_set('UTC');
olegarch
  • 3,670
  • 1
  • 20
  • 19
  • Yes, I do live in "(UTC-05:00) Eastern Time (US & Canada)". This is something I neglected when I was coding. That line solved my problem and made me more aware of timezones when dealing with timestamps. Thank you. – user3666355 May 22 '14 at 19:22
  • OK, I did not guess with your timezone since AM/PM cycle time issue. +7 + (-5) is 12. – olegarch May 22 '14 at 20:37