Scorpioniz - 1 year ago 63
PHP Question

# How to sum two times with milliseconds?

Is there any way to sum two times with milliseconds like this:

``````00:01:02.73
00:03:03.01
``````

to one?

the result should be like this:

``````00:04:05.74
``````

format is simple "
`hours:minutes:seconds.milliseconds`
"

If yes, how?

well I wrote few functions which is helping me to do that

``````\$time1 = "00:15:45.89";
\$time2 = "00:18:30.22";

\$milli1 = timeToMilliseconds(\$time1);
\$milli2 = timeToMilliseconds(\$time2);

\$new = \$milli1 + \$milli2;

\$time = formatMilliseconds(\$new);
echo \$time;

function timeToMilliseconds(\$time){
\$time_start = substr(\$time, -11, -3);
\$time_end = substr(\$time, -3);

\$time_arr = explode(':', \$time_start);
\$seconds = 0;
foreach(\$time_arr as \$key => \$val){
if(\$key == 0){
\$seconds += \$val * 60 * 60;
}elseif(\$key == 1){
\$seconds += \$val * 60;
}elseif(\$key == 2){
\$seconds += \$val;
}
}

\$seconds = \$seconds.\$time_end;
\$milliseconds = \$seconds * 1000;

return \$milliseconds;
}

function formatMilliseconds(\$milliseconds) {
\$seconds = floor(\$milliseconds / 1000);
\$minutes = floor(\$seconds / 60);
\$hours = floor(\$minutes / 60);
\$milliseconds = \$milliseconds % 1000;
\$seconds = \$seconds % 60;
\$minutes = \$minutes % 60;

\$format = '%u:%02u:%02u.%03u';
\$time = sprintf(\$format, \$hours, \$minutes, \$seconds, \$milliseconds);
return rtrim(\$time, '0');
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download