在PHP中将字符串转换为hh:mm时间格式的时间[复制]

在PHP中将字符串转换为hh:mm时间格式的时间[复制]

问题描述:

This question already has an answer here:

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.

</div>

You can use this fastest solution:

$strTime = "0920";
echo $strTime[0] . $strTime[1] . ':' . $strTime[2] . $strTime[3];

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.

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()