Share it

Bookmark and Share

Translate

Wednesday, June 8, 2011

0 PHP: Display seconds as hours, minutes and seconds

Usage is straightforward: pass in a number of seconds, and you'll get a string back along the lines of "1:01:23". If you want a leading zero for less than 10 hours ("01:01:23" in our example), call the function with the second parameter set to true.
//code
 <?php

  function sec2hms ($sec, $padHours = false) 
  {

    // start with a blank string
    $hms = "";
    
    // we divide the total number of seconds by 3600 
       and throw away the remainder
  
   $hours = intval(intval($sec) / 3600); 

    // add hours to $hms (with a leading 0 if asked for)
    $hms .= ($padHours) 
          ? str_pad($hours, 2, "0", STR_PAD_LEFT). ":"
          : $hours. ":";
    
    // dividing the total seconds by 60
    
    $minutes = intval(($sec / 60) % 60); 

    // add minutes to $hms (with a leading 0 if needed)
    $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ":";

    //  dividing the total number of seconds by 60
    
    $seconds = intval($sec % 60); 

    // add seconds to $hms (with a leading 0 if needed)
    $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);

    // done!
    return $hms;
    
  }

?>

0 comments:

Post a Comment

Thanks for your valuable Comment

 

TechnoTipworld- Tips,Tricks,Technology Copyright © 2011 - |- Template created by O Pregador - |- Powered by Blogger Templates