Benjamin Oats Benjamin Oats - 1 month ago 7
MySQL Question

turn int echo milliseconds to minuets and seconds

I have a php query that is getting a filed from my database that contains a int for example 7800, I know that 7800 is 7.7 seconds or 0.13 minuets.

I need a way to display this as

00:00:08 (round up)


The table print out looks like this

<td><?= $row["timeSpent"] ?></td>


it prints out
7800


I need
00:00:08 (H,M,S)


its kept as a INT in the database not datetime

I have tried

<td><? echo gmdate("H:i:s", $row['timeSpent']); ?></td>


except
7.8
seconds prints as
02:10:00

Answer

You just have to use the divide and modulo operators to build your variables, and str_pad to populate your string bits with leading zeros :

<?php 

function convertToTime($time) {
    $time = round($time/1000);
    $hours = floor($time/3600);
    $time = $time%3600;
    $minutes = floor($time/60);
    $seconds = $time%60;
    return str_pad($hours, 2, '0',STR_PAD_LEFT) . ':' . str_pad($minutes, 2, '0',STR_PAD_LEFT) . ':' . str_pad($seconds, 2, '0',STR_PAD_LEFT);
}

var_dump(convertToTime(7800)); // string '00:00:08' (length=8)
var_dump(convertToTime(60000)); // string '00:01:00' (length=8)
var_dump(convertToTime(3600000)); // string '01:00:00' (length=8)
var_dump(convertToTime(42687000)); // string '11:51:27' (length=8)

?>