Tags
Asked 3 years ago
9 Jun 2021
Views 237
jignesh

jignesh posted

How to find the time elapsed since a date time in php ?

How to find the time elapsed since a date time in php ?
steave

steave
answered Apr 26 '23 00:00

To find the time elapsed since a date time in PHP, you can use the DateTime class and its diff() method. Here is an example code snippet:



// Create two DateTime objects for comparison
$currentDateTime = new DateTime();
$oldDateTime = new DateTime('2022-01-01 00:00:00');

// Calculate the time difference
$timeDiff = $oldDateTime->diff($currentDateTime);

// Output the time elapsed

echo "Time elapsed: " . $timeDiff->format('%y years, %m months, %d days, %h hours, %i minutes, %s seconds');
In this example, we create two DateTime objects - one for the current date and time, and another for a specific date and time in the past. We then calculate the time difference between the two dates using the diff() method, which returns a DateInterval object. Finally, we use the format() method of the DateInterval object to format the time difference as a string in years, months, days, hours, minutes, and seconds.
Post Answer