Since you already mentioned that you are using these codes, I assume they both work for you. Now, I have combined them for you into a single function that updates the metadata after a post is published:
function set_date_difference($post_id){
// Get the value of the first field
$date1 = get_field('date_start', $post_id, false );
$date1 = new DateTime( $date1 );
$unix1 = strtotime( $date1->format( 'Y-m-d' ) );
// Get the value of the second field
$date2 = get_field( 'date_dun', $post_id, false );
$date2 = new DateTime( $date2 );
$unix2 = strtotime( $date2->format( 'Y-m-d' ) );
// Calculate the difference
if( 0 === ( $unix1 - $unix2 ) ) {
$days = 0;
} elseif( $unix2 < $unix1 ) {
$days = -1 * ( intval( $unix1 - $unix2 ) / DAY_IN_SECONDS );
} else {
$days = ( intval( $unix2 - $unix1 ) / DAY_IN_SECONDS );
}
// Update the field
update_post_meta($post_id,'difference', $days);
}
add_action('save_post','set_date_difference');
The save_post
action passes the post’s ID to the function, so you can use it to get and update the fields.