I have the following code that tries to calculate hours worked. I'm having a bit of an issue in that hours and minutes always returns zero. My best guess is it has something to do with the new DateTime, but I have no idea how to remedy this.
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
include_once 'functions.php';
$error_msg = "";
sec_session_start();
//Get Username from session id
$username = htmlentities($_SESSION['username']);
//get time date stamp
date_default_timezone_set('America/Chicago'); //set default timezone, just to be sure
//GET Last Clockin from timesheet table
$result = $mysqli->query("SELECT lastclockin FROM timesheet WHERE username = '$username'");
$number_of_rows = $result->num_rows;
while ($row = mysqli_fetch_assoc($result)) {
$lastclockin = $row["lastclockin"];
}
echo $lastclockin;
echo "<br />";
$now = new DateTime();
$diff = $now->diff(new DateTime($lastclockin));
$hours = $diff->h;
$minutes = $diff->m;
$hours = $hours + ($diff->days*24);
echo $now->format('Y-m-d H:i:s');
echo "<br />";
echo $hours;
echo "<br />";
echo $minutes;
echo "<br />";
?>
The results are as follows:
2014-09-11 13:02:15
2014-09-11 13:47:34
0
0
There is zero hours difference between the two times so that makes sense. You'll need to test using two times that are further apart to see a value greater than zero here.
Your minutes are incorrect because m
is the month identifier. i
is for minutes.
$minutes = $diff->i;