Reputation: 47
I am trying to display the length of time a user has been logged in. I have it working except for once thing. The hours part of the time starts at 1 and not 0.
Here is the PHP code:
//Set the local timezone to GMT
date_default_timezone_set('Europe/London');
//Fetch the timestamp for when user logged in
$loggedins = $conn->query ("SELECT Last_Activity FROM students WHERE Full_Name = '$name'");
$loggedinr = $loggedins->fetch_assoc();
$dateloggedin = strtotime($loggedinr['Last_Activity']);
//Separate the time from the above
$timelogin = date("h:i:s", $dateloggedin);
$timenow = date("h:i:s");
//Work out the time spent logged in
$sessionlength = strtotime($timenow)-strtotime($timelogin);
$sessionlength = date("H:i:s", $sessionlength);
** The Last_Activity column in the database contains: 2020-07-08 10:07:58
Here is the HTML:
<p style="line-height: 40px">Session length: <b><?= $sessionlength?></b></p>
This is what the page displays after being logged in for 13mins:
Session length: 01:13:44
The following amendment shows the correct time (00:13:44)
$sessionlength = date("H:i:s", $sessionlength-3600);
Why does it add an hour? Any constructive help would be appreciated.
Upvotes: 2
Views: 49
Reputation: 499
I cannot figure out why it's adding an hour, i think the assumption of Siobham makes the most sense, I tried setting the timezone to simply "Europe" and its printing the correct time, but if i add Paris it adds an hour.
Here is what seems to be a more reliable solution
date_default_timezone_set('Europe/London');
$datetime1 = new DateTime('2020-07-08 10:07:58');//start time
$datetime2 = new DateTime($timenow);//end time
$interval = $datetime1->diff($datetime2);
echo $interval->format('%H:%I:%S');
Upvotes: 2