admin管理员组

文章数量:1122846

We have 3 ACF fields added to Woocommerce orders - start date (pick_up_date), number of weeks (number_of_weeks) and end date (end_date)

Start date and number of weeks are manually entered and the value of the end date field should be calculated based on those 2 values (start date + (7*number_of_weeks) = end date) and correct formatted (d/m/Y), then saved in the end_date field

I have trouble working with the date fields to have the end date calculated correctly. I'd appreciate your help it getting this to work

We have 3 ACF fields added to Woocommerce orders - start date (pick_up_date), number of weeks (number_of_weeks) and end date (end_date)

Start date and number of weeks are manually entered and the value of the end date field should be calculated based on those 2 values (start date + (7*number_of_weeks) = end date) and correct formatted (d/m/Y), then saved in the end_date field

I have trouble working with the date fields to have the end date calculated correctly. I'd appreciate your help it getting this to work

Share Improve this question asked May 5, 2024 at 13:26 nadyawellnadyawell 711 gold badge1 silver badge3 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

You could consider working with unix timestamps (a numerical representation of a date and time that is the seconds elapsed since 00:00:00 1st January 1970). This makes the math easier since we would be working with plain numbers:

// Convert pick up date to unix timestamp integer.
$start_timestamp = strtotime( get_field( 'pick_up_date' ) . ' 00:00:00' );

// Get the number of weeks as seconds:
// 60 - seconds in a minute, minutes in an hour.
// 24 - hours in a day.
//  7 - days in a week.
$weeks_in_seconds = get_field( 'number_of_weeks' ) * 7 * 24 * 60 * 60;

// Add the weeks period of time to our start timestamp.
$end_timestamp = $start_timestamp = $weeks_in_seconds;

// Convert our result timestamp back to a date string.
$end_date = gmdate( 'd/m/Y', $end_timestamp );

This seems to have worked

function UpdateEndDate($post_id){
    
//get start date and number of weeks
$start_date = get_field('pick_up_date',$post_id);
$weeks = get_field('number_of_weeks',$post_id);

// Create and modify the date.
$dateTime = DateTime::createFromFormat('d/m/Y', $start_date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$end_date_final = $dateTime->format('d/m/Y');

    
update_field('end_date',$end_date_final,$post_id); 
    
}
add_action('acf/save_post', 'UpdateEndDate', 20); 

本文标签: woocommerce offtopicCalculate order end date based on date and number of weeks ACF fields