Question

I try to compare two swim times in php. They are like HH:MM:SS.XX (XX are hundreths). I get them as string and i want to find out which swimmer is faster. I tryed to convert them using strtotime(). It works with hours, minutes and seconds but it ignores hundreths. Here is my code for better explanation:

$novy = strtotime($input1); 
$stary = strtotime($input2);
if($novy < $stary){
   //change old(stary) to new(novy)
}

If $input1 is 00:02:14.31 and $input2 is 00:02:14.32 both $novy and $stary are 1392850934. I read some solution to similar problem in javascript but I can`t use it, this must be server-side. Thank you for help.

Was it helpful?

Solution 2

If the format is really HH:MM:SS.XX (ie: with leading 0's), you can just sort them alphabetically:

<?php
$input1 = '00:02:14.31';
$input2 = '00:02:14.32';
if ($input1 < $input2) {
    echo "1 faster\n";
} else {
    echo "2 faster\n";
}

It prints 1 faster

OTHER TIPS

If you use date_create_from_format you can specify the exact date format for php to convert the string representations to:

<?php
$input1 = '00:02:14.31';
$input2 = '00:02:14.32';
$novy = date_create_from_format('H:i:s.u', $input1);
$stary = date_create_from_format('H:i:s.u',$input2);
if ($novy < $stary) {
    echo "1 shorter\n";
} else {
    echo "2 longer\n";
}

Recommended reading: http://ie2.php.net/datetime.createfromformat

You could write some conditional logic to test if HH::MM::SS are identical, then simply compare XX, else use the strtotime() function that you are already using

You are working with durations, not dates. PHP's date and time functions aren't really of any help here. You should parse the string yourself to get a fully numeric duration:

$time = '00:02:14.31';

sscanf($time, '%d:%d:%d.%d', $hours, $minutes, $seconds, $centiseconds);
$total = $centiseconds
       + $seconds * 100
       + $minutes * 60 * 100
       + $hours * 60 * 60 * 100;

var_dump($total);

The total is in centiseconds (100th of a second, the scale of your original input). Multiply/divide by other factors to get in others scales, as needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top