Convert Seconds to Hours, Minutes, Seconds in PHP

Post topics that do not fall under particular product categories here. We will review this forum regularly in order to determine what forums we need to create. If you have a suggestion on forum structure, let us know!

Convert Seconds to Hours, Minutes, Seconds in PHP

Postby dhunt » Thu Sep 18, 2008 5:22 pm

Very often I search for code snippets for a project, and typically I find something fairly elegant that works or only needs minor adjustment. I was recently looking for a method for converting seconds to a MySQL TIME format of Hours, Minutes, and Seconds and was surprised that the functions I found through google were these long functions for breaking down the number and rebuilding it. Something told me that these methods were far too heavy, or at least clumsy to look at. Here is an alternate solution to our problem:

Solution A:
Convert SECONDS to an HH:MM:SS format.

Code: Select all
function format_sec( $sec, $format = 'H:i:s' ){
  return date($format, mktime(0,0,$sec));
}


Wow - simple and very useful... Heck, you don't even need a function for that, just drop the date() code into your output line!

Solution B:
This type of solution is all over the web.. Maybe it is a little faster, but it sure is ugly...
And this is a super slim version!!

Code: Select all
function format_sec($sec) {
  return
    str_pad(intval(intval($sec) / 3600), 2, "0", STR_PAD_LEFT)  // hours
    . ':'
    . str_pad(intval(($sec / 60) % 60), 2, "0", STR_PAD_LEFT)   // minutes
    . ':'
    . str_pad(intval($sec % 60), 2, "0", STR_PAD_LEFT);         // seconds
}


I ran both functions in a loop 1 million times on a WinXP machine...
Solution A - 10.7407 seconds
Solution B - 9.4821 seconds

I ran both functions in a loop 1 million times on a Unix machine...
Solution A - 10.5965 seconds
Solution B - 6.4008 seconds

Since I'm not running it a million times... I'm going to stick with Solution A.
It is interesting how much faster the Unix box is to run the Solution B...
dhunt
 
Posts: 57
Joined: Sat Aug 02, 2008 7:04 pm

Re: Convert Seconds to Hours, Minutes, Seconds in PHP

Postby dhunt » Sat Sep 20, 2008 6:38 pm

Well I just got word back that Solution A breaks if the seconds input is greater than 86400 seconds (1 day) - phewie...

Back to Solution B....
dhunt
 
Posts: 57
Joined: Sat Aug 02, 2008 7:04 pm


Return to General Developer Topics

Who is online

Users browsing this forum: No registered users and 1 guest

cron