Converting Seconds to H:M:S in PHP the Easiest Way
Tuesday, September 20th, 2011While feeling lazy tonight at the end of a coding run, I discovered the easiest time conversion trick yet. After finding a number of scripts longer than my arm to accomplish something I consider trivial, I dare say I’ve come up with the easiest way to do this all by myself.
<?php $hms = gmdate('H:i:s',$seconds); ?>
Pretty sweet, no? The trick here is to tell PHP your date is in reference to the Unix epoch, and make sure you do it in GMT (a la gmdate) so it doesn’t try to take your time zone into account. This example works for up to 24 hours, so if you need more than that, consider the following two examples:
Allowing the function to display days:
<?php $hms = gmdate('d:H:i:s',$seconds); ?>
Allowing the function to display more than 24 hours:
<?php $hms = floor($seconds/3600).gmdate(':i:s',$seconds); ?>
You can change the format as well, per the normal php date() function’s format. Enjoy!
