简体   繁体   中英

Display date range from 2 custom date-picker fields

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!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM