Difference between two dates in php

php-programming
Difference between two dates in php
30 Nov 2023 91 views
There are many methods have to find out difference between two dates in php. A perfect method is using diff() function.

diff() is a built-in function php.

Please find the below example function.

function dateDifference($date1, $date2) {
    $dateTime1 = new DateTime($date1);
    $dateTime2 = new DateTime($date2);
    $interval = $dateTime1->diff($dateTime2);
    $result='';
    if ($interval->y > 0) {
        $result.=$interval->y . ' year(s) ';
    }
    if ($interval->m > 0) {
        $result.=$interval->m . ' month(s) ';
    }
    if ($interval->d > 0) {
        $result.=$interval->d . ' day(s)';
    } 
    
    return $result;
}

You  can run the result using this

echo dateDifference('2023-2-5', '2024-5-2');

You will get this result

1 year(s) 2 month(s) 27 day(s)