Page 1 of 1

Problem with date() function

Posted: Tue Jan 18, 2011 9:35 pm
by slick1537
Hello all!

New php coder here. I am working on a project that has a timer in it. The timer displays the elapsed time to the user. My code is not complete yet but I have been getting unintended results and I cannot figure out why. I am hoping someone would shed some light on it. The code puts a start timestamp into the database, then to get the time elapsed since the start timestamp it is subtracted from the current timestamp. The "i:s" work as intended, however for some reason the "H:" is returning 19, I have no idea why. I also tried using the php datetime object to generate timestamps but got the same results.

Code: Select all

<?php

$sql = new mysqli('localhost', 'joeuser', 'somepass', 'database');
	if ($sql -> connect_errno) {
		printf ("Connection failed: %s\n", $sql -> connect_error);
		die();
	}
	
$session_id = 1;
	
$stmt = $sql -> prepare("select start_time, elapsed_time from session where session_id = ?");
$stmt -> bind_param("i", $session_id);
$stmt -> execute();
$stmt -> store_result();
$stmt -> bind_result($start_time, $elapsed_time);
$stmt -> fetch();

if ($start_time == 0) {
	$start_time = mktime(); 
	$sql -> query("UPDATE session SET  start_time =  $start_time WHERE  session_id = $session_id LIMIT 1");
}

$end_time = mktime();
$elapsed_time = $end_time - $start_time;
echo date("H:i:s", $elapsed_time);

$stmt -> close();
$sql -> close();
?>

Re: Problem with date() function

Posted: Tue Jan 18, 2011 9:50 pm
by Jonah Bron
I don't think it's as easy as that. Date/time difference calculation is complicated. You need to extract the number of hours from the difference, then the minutes, and then the seconds remain. Like this:

Code: Select all

$timestamp = 3661; // sample difference, equates to one hour, one minute, and one second.

$hours = floor($timestamp / (60 * 60));
$timestamp = $timestamp % (60 * 60);

$minutes = floor($timestamp / 60);
$seconds = $timestamp % 60;
Tested, functions as expected. Do you see how that works?

(Note, the % symbol gets the remainder from the division. See here: http://php.net/operators.arithmetic)

Update: I made a post on my blog about it, explaining things further: http://nucleussystems.com/blog/calculat ... difference

Re: Problem with date() function

Posted: Wed Jan 19, 2011 8:36 am
by slick1537
Thanks alot!

I appreciate you helping me out with my problem. The code is working as intended now. I will also add if there is anyone else out there with a similar problem I used...

Code: Select all

printf("%02s:%02s:%02s", $hours, $minutes, $seconds);
...to pad variables the number with a leading zero when it happened to be less than 2 digits long.