Given the time in hours, minutes and seconds, compute the total number of seconds that have elapsed since midnight.
This solution seems almost like cheating because it doesn't use any date functions. However, it outputs the correct result.
<? // i'm going to use the current time, rather than making one up $hours = date(H); $minutes = date(i); $seconds = date(s); // add seconds to the total // add seconds contained within minutes // add seconds contained within hours // the brackets aren't required, they just make it easier to understand $since_midnight = $seconds + ($minutes * 60) + ($hours * 3600); // output the final result echo 'Seconds since midnight: ' . $since_midnight;?>Which produces:
Seconds since midnight: 29734
One way to work out the number of seconds that have elapsed since midnight at the current time would be like this:
<? // time() returns the seconds since unix epoch for the current time // strtotime('00:00') returns the seconds since the unix epoch for last midnight // so taking away the midnight time from the current time, gives the correct result // instead of 00:00, nothing could be used, but that causes problems with php 4.3.8 echo 'Seconds since midnight: ' . (time() - strtotime('00:00'));?>Which produces:
Seconds since midnight: 29734