php get time difference by milliseconds

this is a function that calculates the difference between two times with milliseconds. i built it for a racing website to compare drivers.

function find_time_diff($t1, $t2, $ms=false) {
    $time1_pcs = explode(":", $t1);
	$time1_pcs2 = explode(".", $time1_pcs[2]);
	
    $time2_pcs = explode(":", $t2);
	$time2_pcs2 = explode(".", $time2_pcs[2]);
	
	$time1_all_ms = ($time1_pcs[0] * 60 * 60 * 1000) + ($time1_pcs[1] * 60 * 1000) + ($time1_pcs2[0] * 1000) + $time1_pcs2[1];
	$time2_all_ms = ($time2_pcs[0] * 60 * 60 * 1000) + ($time2_pcs[1] * 60 * 1000) + ($time2_pcs2[0] * 1000) + $time2_pcs2[1];
	$time1_all_ms_dif = $time2_all_ms - $time1_all_ms;
if($ms){
return $time1_all_ms_dif;
}
else{
	$dif_ms = $time1_all_ms_dif % 1000;
	$time1_all_ms_dif = floor($time1_all_ms_dif / 1000);

	$dif_s = $time1_all_ms_dif % 60;
	$time1_all_ms_dif = floor($time1_all_ms_dif / 60);

	$dif_m = $time1_all_ms_dif % 60;
	$time1_all_ms_dif = floor($time1_all_ms_dif / 60); 
	$dif_h = $time1_all_ms_dif % 60;

	return $dif_h.':'.$dif_m.':'.$dif_s.'.'.$dif_ms;
	}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *