J Cornelius

Converting Seconds in PHP

All of the conversion functions that I found seemed really bloated. Here is a nice clean way to convert seconds to a more user friendly hour:minute:seconds format. This example takes the current Unix time and converts it to the desired format. Of course you can use this for just about any application that requires you to convert seconds to a more readable format. $seconds = time(); $time = str_pad(intval(intval($seconds/3600)),2,"0",STR_PAD_LEFT).":" . str_pad(intval(($seconds / 60) % 60),2,"0",STR_PAD_LEFT).":" . str_pad(intval($seconds % 60),2,"0",STR_PAD_LEFT) ; Now let's use this code for printing the time a particular script (or function) takes to run. Snazzy ! $start = time(); //--> some code here $finish = time(); $sec = ($finish - $start); $runtime = str_pad(intval(intval($sec) / 3600),2,"0",STR_PAD_LEFT).":" . str_pad(intval(($sec / 60) % 60),2,"0",STR_PAD_LEFT).":" . str_pad(intval($sec % 60),2,"0",STR_PAD_LEFT) ;
Published: Short URL: http://jc.cm/5/
Bookmark using Delicious Share on Tumblr Share on Posterous