Skip to content
Advertisement

Round football match clock to the nearest minute PHP

I’m trying to round the minutes of a football match clock in PHP. The given format is: 70:38 and I want to round it to the nearest minute: 71:00.

Note: A football match consists of two halves and each half is 45 minutes long.

Code:

$matchClock = '45:20';

$time = strtotime('0:'.$matchClock.'');
$rounded = round($time / 60) * 60;
echo date("i:s", $rounded);
$matchClock = '45:20';

I have two problems:

  1. Inside strtotime() I have to use H otherwise it returns zero. Should I use it?
  2. When the match clock is beyond 60:00 it zeros everything.

Any suggestions?

Thank you

Advertisement

Answer

Simplify the problem. If you’re always getting the same format, explode it on the colon to get the minutes and seconds. If the seconds are greater than or equal to 30, add one to the minutes, otherwise they stay the same. It will always be 00 seconds so attach that to the minutes at the end.

$arr = explode(“:”, $time);
$minutes = (int) $arr[0];
$seconds = (int) $arr[1];

If ($seconds >= 30){
$minutes++;
}

$answer = $minutes.”:”.”00”;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement