I have the following simple code for testing:
$start_time_unix = time();
$end_time_unix = time();
$seconds_diff = $end_time_unix - $start_time_unix;
$duration = round(abs($seconds_diff/1000) / 60,2);
When i store it in MySQL (int), the results are big values like 25634 even for a few seconds. How can i get the minutes, even in fraction of minutes?? What is wrong with my code above ??
First of all int
cannot store fractions, so you will probably want to use float
or double
instead.
But why are you dividing by 1000
. $seconds_diff
consists of a seconds, so dividing by 60
will give you fraction of a minute.
For example: If $seconds_diff
is a value of 13
[seconds]:
$duration_in_minutes = round($seconds_diff / 60, 2);
$duration_in_milliseconds = $seconds_diff * 1000;
If it is your goal to use milliseconds then use microtime()
instead of time()
: http://php.net/manual/de/function.microtime.php
Recommendation
Just measure the time with microtime()
and directly store the result in the database without rounding, dividing or formatting. Then later on, do the formatting when you have to output it. This will give you more precise results and more freedom.
$start_time = microtime();
…
$end_time = microtime();
$duration = $end_time - $start_time; // duration in milliseconds --> save to database
When outputting, for example:
$duration = get_duration_from_database(); // pseudo function
printf('%.2f minutes', $duration / 1000 / 60);
The time()
function returns the current Unix timestamp in seconds. There is no need to divide it by 1000. Since MySQL is expecting an integer, you must round to 0 decimal places:
$seconds_diff = abs($end_time_unix - $start_time_unix);
$duration = round($seconds_diff / 60, 0);