How to calculate time difference between two dates in PHP?

by elwin_wilderman , in category: PHP , 2 years ago

How to calculate time difference between two dates in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by craig , 2 years ago

@elwin_wilderman You can use DateTime() object to calculate time difference between two dates in PHP, here is code example:


1
2
3
4
5
6
7
8
9
<?php

$now = new DateTime("now");
$yesterday = new DateTime("yesterday");

$diff = $now->diff($yesterday);

// Output: 1 day(s)
echo $diff->format('%d day(s)');


Member

by freddy , a year ago

@elwin_wilderman 

In PHP, you can use the built-in function DateTime::diff() to calculate the time difference between two dates. Here's an example:

1
2
3
4
$datetime1 = new DateTime('2022-01-01');
$datetime2 = new DateTime('2022-01-31');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');


In this example, we create two DateTime objects representing the dates we want to compare. We then call the diff() method on the first DateTime object, passing in the second DateTime object as an argument. This returns a DateInterval object representing the difference between the two dates.


We then use the format() method of the DateInterval object to format the difference as a string. The %R character prints a plus sign if the difference is positive, a minus sign if it is negative, and nothing if it is zero. The %a character prints the difference in days.


You can use other characters to format the output as well, such as %h for hours, %i for minutes, %s for seconds, and so on.