Calculate days between two custom field value dates

We can use something like human_time_diff() to give us a readable time difference. First we need to see if the days are the same:

$date1 = get_field( 'date_start', false, false );
$date1 = new DateTime( $date1 );
$unix1 = strtotime( $date1->format( 'Y-m-d' ) );

$date2 = get_field( 'date_fin', false, false );
$date2 = new DateTime( $date2 )
$unix2 = strtotime( $date2->format( 'Y-m-d' ) );

if( 0 === ( $unix1 - $unix2 ) ) {
    echo 'On Time!';
} elseif( $unix2 < $unix1 ) {
    echo human_time_diff( $unix1, $unix2 ) . ' Early';
} else {
    echo human_time_diff( $unix1, $unix2 ) . ' Late';
}

Some example with output:

Date 1 = June 3rd
Date 2 = June 3rd
Output: On Time!

Date 1 = June 10th
Date 2 = June 13th
Output: 3 Days Late

Date 1 = June 10th
Date 2 = June 3rd
Output: 1 Week Early


If we wanted to show the actual days instead of week or month as human_time_diff() does we can just subtract the largest from the smallest, divide by the WordPress constant variable DAY_IN_SECONDS. We’ll then run it through the _n() function to display plural or singular.

if( 0 === ( $unix1 - $unix2 ) ) {
    echo 'On Time!';
} elseif( $unix2 < $unix1 ) {
    $days = ( intval( $unix1 - $unix2 ) / DAY_IN_SECONDS );
    printf( _n( '%s day early', '%s days early', $days ), $days );
} else {
    $days = ( intval( $unix2 - $unix1 ) / DAY_IN_SECONDS );
    printf( _n( '%s day late', '%s days late', $days ), $days );
}