# 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 84862:
23 hour(s), 34 minute(s) and 22 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 63983:
17 hour(s), 46 minute(s) and 23 second(s)

## Log

• April 2, 2005 - Added solution 1 and 2.
© 2004-19 robson | cc unless stated