Search code examples
phpdatewoocommerceaction

wrong date appearance as custom field


I just tried to add a "Delivery Date" to WooCommerce checkout process based on this and this threads.

This is the related code to print delivery date on order meta and view it on Thank you page and also admin order page:

//Shipping (Delivery) Date


// Add custom checkout datepicker field

add_action( 'woocommerce_before_order_notes', 'checkout_display_datepicker_custom_field' );
function checkout_display_datepicker_custom_field( $checkout ) {
    $field_id = 'my_datepicker';

    echo '<div id="datepicker-wrapper">';

    $today = strtotime('today');
    $tomorrow = strtotime('tomorrow');
    $dayAfterTomorrow = strtotime('+2 days');

    woocommerce_form_field(  $field_id, array(
        'type'          => 'select',
        'class'         => array('my-field-class form-row-wide'),
        'label' => __('Choose a date'),
        'placeholder'   => __('Select delivery date'),
        'required' => true, // Or false
        'options'     => array(
            '' => 'Select',
            date( 'yyyy-mm-dd', $today ) => date( get_option('date_format'), $today ),
            date( 'yyyy-mm-dd', $tomorrow ) => date( get_option('date_format'), $tomorrow ),
            date( 'yyyy-mm-dd', $dayAfterTomorrow ) => date( get_option('date_format'), $dayAfterTomorrow ),
        )));

    echo '<br></div>';

}



// Save field

add_action( 'woocommerce_checkout_create_order', 'save_datepicker_custom_field_value', 10, 2 );
function save_datepicker_custom_field_value( $order, $data ){
    $field_id = 'my_datepicker';
    $meta_key = '_'.$field_id;

    if ( isset($_POST[$field_id]) && ! empty($_POST[$field_id]) ) {
        $date = esc_attr($_POST[$field_id]);
        
        $order->update_meta_data( $meta_key, $date ); // Save date as order meta data
        
        $note = sprintf(__("Chosen date for Thank you page: %s.", "woocommerce"), $date );
        $note = isset($data['order_comments']) && ! empty($data['order_comments']) ? $data['order_comments'] . '. ' . $note : $note;
        
        // Save date on customer order note
        $order->set_customer_note( $note );

    }
}

It prints choosed date but in a wrong format like: 20202020-1212-2424

How can I modify this bug?


Solution

  • You're using the wrong format on your date() functions. Have a look at date/time format docs.

    In your case, yyyy-mm-dd:

    • y A two digit representation of a year
    • m Numeric representation of a month, with leading zeros
    • d Day of the month, 2 digits with leading zeros

    Hence, 20202020-1212-2424.

    You probably meant 2020-12-24, which should be Y-m-d:

    • Y A full numeric representation of a year, 4 digits