How to check time between 2 date variables in php?

by muriel.schmidt , in category: PHP General , 9 months ago

How to check time between 2 date variables in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 9 months ago

@muriel.schmidt 

You can calculate the time between two date variables in PHP using the DateTime class. Here is an example of how to do this:

1
2
3
4
5
6
$date1 = new DateTime('2022-01-01');
$date2 = new DateTime('2022-02-01');

$interval = $date1->diff($date2);

echo $interval->format('%R%a days'); // Output the time difference in days


In this example, we create two DateTime objects representing the two dates you want to compare. We then use the diff() method to calculate the difference between the two dates, which is returned as a DateInterval object. Finally, we use the format() method to output the time difference in days.


You can also output the time difference in other formats such as hours, minutes, seconds, etc., by changing the format string in the format() method.