I have to calculate date time difference, how to do that in PHP? I need exact hours, mins and secs. Anybody have the scripts for that?
6 Answers
Use the diff() method of PHP's DateTime class like this:-
$lastWeek = new DateTime('last thursday'); $now = new DateTime(); var_dump($now->diff($lastWeek, true)); This will give you a DateInterval object:-
object(DateInterval)[48] public 'y' => int 0 public 'm' => int 0 public 'd' => int 2 public 'h' => int 11 public 'i' => int 34 public 's' => int 41 public 'invert' => int 0 public 'days' => int 2 Retrieving the values you want from that is trivial.
Comments
Check this.. This should work
<?php function timeDiff($firstTime,$lastTime) { // convert to unix timestamps $firstTime=strtotime($firstTime); $lastTime=strtotime($lastTime); // perform subtraction to get the difference (in seconds) between times $timeDiff=$lastTime-$firstTime; // return the difference return $timeDiff; } //Usage : echo timeDiff("2002-04-16 10:00:00","2002-03-16 18:56:32"); ?> 4 Comments
This should work, just replace the times in the time diff with the time the task started and the current time or the time the task had ended. For a continuous counter the start time would be stored in a database, or for elapsed time for a task the end time would as well
function timeDiff($firstTime,$lastTime){ // convert to unix timestamps $firstTime=strtotime($firstTime); $lastTime=strtotime($lastTime); // perform subtraction to get the difference (in seconds) between times $timeDiff=$lastTime-$firstTime; // return the difference return $timeDiff; } //Usage : $difference = timeDiff("2002-03-16 10:00:00",date("Y-m-d H:i:s")); $years = abs(floor($difference / 31536000)); $days = abs(floor(($difference-($years * 31536000))/86400)); $hours = abs(floor(($difference-($years * 31536000)-($days * 86400))/3600)); $mins = abs(floor(($difference-($years * 31536000)-($days * 86400)-($hours * 3600))/60));#floor($difference / 60); echo "<p>Time Passed: " . $years . " Years, " . $days . " Days, " . $hours . " Hours, " . $mins . " Minutes.</p>"; Comments
For something like that use the built int time() function.
- Store the value of
time();something like1274467343which is the number of seconds since - When ever needed retrieve the value and assign it to
$erlierTime. - Assign
time()again to the latter stop time you would want, lets just call it$latterTime
So now you have something like $erlierTime and $latterTime.
Now just do $latterTime - $erlierTime to get the difference in seconds and then do your divisions to get numb of minutes passed, num of hours passed etc.
In order for me or any one to give you a complete script you would need to tell us what your environment is like and what are you working with mysql, sqlite etc... also would need to know how that timer is triggered.