| ||||||
|
Calculating time differences in PHP by converting seconds into days hours and minutes
Most programmers go about this task the wrong way. Or rather they only complete half the job, and then wonder why they are not getting the intended results. Usually they do something along the lines of subtracting an old timestamp from the current one, which is actually a step in the right direction, but then they get frustrated when strftime() returns them some date from the 70s. Think about the concept of the Unix timestamp for a moment. It has been counting every second since the 1st of January 1970. All Unix time conversion functions are based upon that date. Clearly then a function like strftime() will be of no use to us at all. When you give strftime() the value of 1000 seconds to evaluate it will see it as 1000 seconds past the 1st of January 1970. On the Brightside however we do have the difference between two dates stored in seconds. Meaning all that is needed is a little function to convert these seconds into days, hours, and minutes. Here is how it is done: <?php //Set a fixed point in time $time1 = 1238704848; //Get current Unix time stamp $time2 = time(); //Calculate the difference in seconds $difference = $time2 - $time1; $diffSeconds = $difference; //Calculate how many days are within $difference $days = intval($difference / 86400); //Keep the remainder $difference = $difference % 86400; //Calculate how many hours are within $difference $hours = intval($difference / 3600); //Keep the remainder $difference = $difference % 3600; //Calculate how many minutes are within $difference $minutes = intval($difference / 60); //Keep the remainder $difference = $difference % 60; //Calculate how many seconds are within $difference $seconds = intval($difference); //Output: echo "Time1: ".strftime("Time: %H:%M:%S Date %d %B %Y", $time1); echo "<br><br>"; echo "Time2: ".strftime("Time: %H:%M:%S Date %d %B %Y", $time2); echo "<br><br>"; echo "Difference in seconds: ".$diffSeconds; echo "<br><br>"; echo "Difference in Days: ".$days." Hours: ".$hours." Minutes: ".$minutes." Seconds: ".$seconds; ?>
|