John Davidson

php - Display time with 1 zero when seconds is less or equal to 60 seconds


I'm displaying videos and I want to show the duration. Im using the following:

echo ltrim(date('i:s', $vduration), '0')


But, if the video is 40 seconds only. The formula doesn't work. It shows


Basically, if the video is less then 60 seconds, it should show 1 zero only (not 2), like so:


Is there a magic formula for this or do I need to use conditions to check if less or equal to 60 seconds?

My Answer:
You can achieve this by using a conditional statement to check if the duration is less than or equal to 60 seconds. Here's an example code snippet:

$vduration = 40; // Example video duration in seconds

if ($vduration <= 60) {
echo '0:' . str_pad($vduration, 2, '0', STR_PAD_LEFT);
} else {
echo ltrim(date('i:s', $vduration), '0');

This code will display the video duration as "0:40" if the duration is less than or equal to 60 seconds, and in the regular format (e.g. "5:40") if the duration is more than 60 seconds.

Rate this post

3 of 5 based on 9115 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us