MySQL时间格式转换异常:3:56未转为00:03:56而是03:56:00
Ah, I see the issue here! The problem is how strtotime() interprets short time strings like 3:56 — it defaults to parsing that as hours:minutes instead of the minutes:seconds you're expecting. That's why you're getting 03:56:00 instead of 00:03:56.
Let me break down how to fix this with two reliable approaches:
Approach 1: Manual String Parsing (Simple & Direct)
Since your duration strings follow two consistent formats (mm:ss or hh:mm:ss), we can split the string by colons and build the correct time string ourselves:
<?php $durs = array( '3:56', '1:11:00', '2:04:56' ); foreach ($durs as $dur){ $timeParts = explode(':', $dur); if (count($timeParts) === 2) { // Format is minutes:seconds → convert to 00:mm:ss $formattedTime = sprintf('00:%02d:%02d', $timeParts[0], $timeParts[1]); } else { // Format is hours:minutes:seconds → ensure leading zeros are present $formattedTime = sprintf('%02d:%02d:%02d', $timeParts[0], $timeParts[1], $timeParts[2]); } echo $formattedTime . '<br>'; } ?>
This will output exactly what you want:
00:03:56 01:11:00 02:04:56
Approach 2: Use DateTime for Flexibility
If you ever need to do more complex time calculations later, using PHP's DateTime class is a cleaner approach. We start from a base time (00:00:00) and add the duration components:
<?php $durs = array( '3:56', '1:11:00', '2:04:56' ); foreach ($durs as $dur){ $baseTime = new DateTime('00:00:00'); $timeParts = explode(':', $dur); if (count($timeParts) === 2) { $baseTime->modify("+$timeParts[0] minutes +$timeParts[1] seconds"); } else { $baseTime->modify("+$timeParts[0] hours +$timeParts[1] minutes +$timeParts[2] seconds"); } echo $baseTime->format('H:i:s') . '<br>'; } ?>
This gives the same correct output, and it's easier to extend if you need to handle edge cases (like durations longer than 24 hours, though MySQL's TIME type supports that too).
Just a quick note: These formatted strings are fully compatible with MySQL's TIME data type, so you can insert them directly into your database without any extra conversion.
内容的提问来源于stack exchange,提问作者urbmake

