0

We have a lot of strings for storing the time that it took participants to finish the track. There are basically 2 different types of those strings ( <1 hour and >1hour ):

54:37
01:12:20

What would be the most reasonable way to format these strings in PHP before displaying so that they would keep the same standard - hh:mm:ss (the first string needs to be 00:54:37 )?

Any help or guindace is much appreciated.

1

3 Answers 3

2

Simple way would be

$time = str_pad($time,8,'00:',STR_PAD_LEFT)

What it does: Fill the string with 00: from left to the full lenght of 8

or $time = strlen($time)==8?$time:"00:$time"

What it does: Check if string is 8 chars then do nothing else add 00:

This are solutions if really only the 2 different types are given.

This wont work: print date('H:i:s',strtotime('54:37'))

Sign up to request clarification or add additional context in comments.

Comments

1

How about this:

$str = '54:37';
echo str_pad($str, 8, '00:', STR_PAD_LEFT); // outputs 00:54:37

$str = '01:12:20';
echo str_pad($str, 8, '00:', STR_PAD_LEFT); // outputs 01:12:20

Comments

1

If the strings are always delimited with : then you could use explode to split the string into an array and then test to see if that array has two or three elements.

If the array has two elements then you could add "00" to the beginning of the array with array_unshift.

Afterwards you can get a string representation of the array by using implode.

Something along the lines of:

function formatTime ($string) {

   $arr = explode(':', $string);

   if (count($arr) === 2){
       array_unshift($arr, "00");
   }

   return implode(':', $arr);

}

echo formatTime('54:37'); // returns 00:54:37

Of course, you would need to check the validity of the incoming time stamp so that it correctly converted 65:32 into 01:05:32.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.