Display date range from 2 custom date-picker fields

403 views Asked by At

I've created two custom datepicker fields with ACF (beginning_date and completion_date) and need to output/display these as a date range.

For example, if beginning_date Year and completion_date Year are equal, I need to output beginning_date day/month - completion day/month/year.

The display and return format these fields use is: l, F j, Y

I've searched everywhere! And tried to implement this: Create display date range from two dates in ACF in Wordpress

I also attempted to convert the fields to datetime objects but comparing these as dates seems to be the wrong way! I do not know where else I'm failing at... I'm beginning again as nothing has worked so far, so I have no code to publish here because I ended up with a Frankenstein code snippet which I deleted and then came here for desperate help!

1

There are 1 answers

15
Moishy On

in your functions.php

 function date_compare($id){
    
    $start_date = get_field('beginning_date', $id);
    $end_date = get_field('completion_date', $id);
    
    $start_year = wp_date("Y", strtotime( $start_date ) );
    $end_year = wp_date("Y", strtotime( $start_date ) );
    
    $start_month = wp_date("n", strtotime( $start_date ) );
    $end_month = wp_date("n", strtotime( $start_date ) );
    
    $date_output = '';
    
    $start_date_format = "l, F j, Y";
    
    if( $start_date && $end_date ){
        
        if( $start_year == $end_year && $start_month == $end_month ){
            $start_date_format = "l j";
        }
        elseif( $start_year == $end_year){
            $start_date_format = "l, F j";
        }

    }
    
    
    if( $start_date ){
        $date_output .= wp_date($start_date_format, strtotime( $start_date ) );
    }
    
    if( $end_date ){
        $date_output .= ' - ' . wp_date("l, F j, Y", strtotime( $end_date ) );
    }
    
    return $date_output;
}

and in your theme:

echo date_compare($post->ID);