Find days between two dates with PHP

At the first look, the task to calculate the diff in days between two dates seems pretty simple to solve: Just subtract the unix timestamps from the dates and divide the result by 86400 (24 hours * 60 minutes * 60 seconds = one day). But for this calculation we have to take leap seconds into account and also make sure, that the timestamps are at the start of the day. Regardless, let's program this intuitive solution anyway:

function get_diff_days($date2, $date1) {
    $now = strtotime($date2);
    $your_date = strtotime($date1);
    $datediff = $now - $your_date;
    return floor($datediff / (60 * 60 * 24));
}
echo get_diff_days('2023-01-01', '2022-01-01');
// 365

The best and the simplest solution is to use the DateTime class:

function get_diff_days($date2, $date1) {
    $date_start = new DateTime($date1);
    $date_end = new DateTime($date2);
    return $date_end->diff($date_start)->format('%a');
}
echo get_diff_days('2023-01-01', '2022-01-01');
// 365

We can also use the GregorianToJD function to convert our dates from the Gregorian calendar to the Julian date and get the number of days since 01/01/4713 BC and than simply subtract the results:

function get_diff_days($end, $begin){
    $date_format = 'Ymd';
    $sep = '-';

    $pos1 = strpos($date_format, 'd');
    $pos2 = strpos($date_format, 'm');
    $pos3 = strpos($date_format, 'Y');

    $begin = explode($sep, $begin);
    $end = explode($sep, $end);

    $end_days = GregorianToJD($end[$pos2], $end[$pos1], $end[$pos3]);
    $start_days = GregorianToJD($begin[$pos2], $begin[$pos1], $begin[$pos3]);

    return $end_days - $start_days;
}
echo get_diff_days('2023-01-01', '2022-01-01');
// 365