Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding a time on the left with sprintf?

Tags:

php

printf

I'm trying to pad a time (playtime of an MP3) using sprintf() in PHP.

sprintf("%02d:2d:2d", $time);

The function that returns the time gets, for example, '1:56' if the MP3 is 1 minute 56 seconds long, and that call brings back "01:56:00" (whereas it needs to be 00:01:56). How can I make this work? How can I tell sprintf to pad on the left?

Or is there a better way to go about this? A more appropriate function maybe?

Thanks

like image 316
Delameko Avatar asked Dec 28 '25 22:12

Delameko


2 Answers

I think you'll need to calculate each element separately, so how about:

sprintf("%02d:%02d:%02d", floor($time/3600), floor($time/60)%60, $time%60);
like image 167
Paul Dixon Avatar answered Dec 31 '25 11:12

Paul Dixon


You can use the date-function.

Something like this should work, if $time is in unix timestamp format:

print(date("H:i:s", $time));
like image 34
Espo Avatar answered Dec 31 '25 13:12

Espo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!