0

I have a string like-

$strTime = "0920"

How to convert the above string to time format in PHP-

0920 -> 09:20

I am super new to PHP so may be this is a very basic question, I tried with strtotime method but it didn't give me the expected output.

Abhishek Choudhary
  • 8,255
  • 19
  • 69
  • 128

3 Answers3

1

You can use this fastest solution:

$strTime = "0920";
echo $strTime[0] . $strTime[1] . ':' . $strTime[2] . $strTime[3];
Zemistr
  • 1,049
  • 7
  • 10
0

If you know that the format will always be the same you can do it literally:

I found an example here: Split string into 2 pieces by length using PHP

$a = ":"
$first400 = substr($str, 0, 2);
$theRest = substr($str, 2);

Then create the new time string:

echo "$first400{$a}$theRest"

I used basic string mania from here: http://www.php.net/manual/en/language.operators.string.php You could do some basic checks to make sure it's formatted correctly. Ex if it is 4 chars in length.

Community
  • 1
  • 1
Tai
  • 1,206
  • 5
  • 23
  • 48
0

strtotime() gives you the number of seconds since January 1 1970. 920 seconds from that cold, dark birth of time is not the specific time you're looking for.

If you really want that string as your output, with the colon in the middle, I would use just inject the colon into the string with substr_replace()

David Wyly
  • 1,671
  • 1
  • 11
  • 19