Robson » Little Red Book » Time #2

Chapter 1 - Question 4

Given the number of seconds that have elapsed since midnight, compute the time in hours, minutes and seconds.

Solution 1

Here's a quick method:

<?
   // a random number of seconds
   $seconds = mt_rand(1, 86400);
   // output the hours, minutes and seconds that have elapsed    
   echo 'For ' . $seconds . ':<br/>'
      . intval($seconds / 3600) . ' hour(s), '
      . intval(($seconds % 3600) / 60) . ' minute(s) and '
      . $seconds % 60 . ' second(s)<br/>';
?>

Which produces:

For 5053:
1 hour(s), 24 minute(s) and 13 second(s)

Solution 2

A method using date functions:

<?
   // store the number of seconds per day
   define(SECONDS_PER_DAY, 86400);
 
   // a random number of seconds
   $seconds = mt_rand(1, SECONDS_PER_DAY);
 
   // get the time at the start of today
   // and then add on the seconds
   $elapsed = strtotime('00:00') + $seconds;
   
   // output the hours, minutes and seconds that have elapsed    
   // intval is used to remove leading zero's
   echo 'For ' . $seconds . ':<br/>'                  // total seconds
      . date(G, $elapsed) . ' hour(s), '              // hours
      . intval(date(i, $elapsed)) . ' minute(s) and ' // minutes
      . intval(date(s, $elapsed)) . ' second(s)';     // seconds
?>

Which produces:

For 14291:
3 hour(s), 58 minute(s) and 11 second(s)

Log

© 2004-17 robson | cc unless stated