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?
In this article, we will learn how to get time difference in minutes using PHP. We will be using the built-in function date_diff() to get the time difference in minutes. For this, we will be needed a start date and end date to calculate their time difference in minutes using the date_diff() function.
The difference is calculated by subtracting the second operand from the first. The result is rounded down, with any remainder discarded. For example, 61 minutes is equal to 1 hour, and 59 minutes is equal to 0 hours.
Total seconds between times: To get the total seconds between two times, you multiply the time difference by 86400, which is the number of seconds in one day (24 hours * 60 minutes * 60 seconds = 86400). Note.
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.
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>";
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");
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With