How to Compare Two Dates in the Same Form

Introduction

Would you like to compare two dates inside the same form? Using a small PHP snippet you can easily take two dates and compare them inside the same form. In this tutorial, we’re going to a PHP snippet that will take two date pickers inside the same form.

Creating the form

First, we’ll need to set up our form. We’re going to create a form and add our fields including the two Date form fields that are set to the Date format.

create your form and add your fields including your 2 date fields

Once you’ve added these fields, be sure to set them to Date Picker on the Advanced tab.

set the date field to use the date picker for both fields

If you need any help in creating your form, please review this documentation.

Adding the snippet to compare two dates

Before adding the snippet, you’ll need to locate the form ID and both field IDs for the Date fields you’ve just added to your form.

If you need any help in finding these ID numbers, please see this tutorial.

When you’ve got these IDs you can add the following snippet to your site.

/**
 * Compare 2 dates inside the same form.
 *
 * @link  https://wpforms.com/developers/how-to-compare-two-dates-in-the-same-form/
 */

function wpf_dev_compare_dates( $fields, $entry, $form_data ) {
      
    // Optional, you can limit to specific forms. Below, we restrict output to
    // form #731.
    if ( absint( $form_data[ 'id' ] ) !== 731 ) {
        return $fields;
    }
      
	// 3 is the ID of date 1 field
	$date_1 = $fields[3][ 'unix' ]; 
	
	// 4 is the ID of date 2 field
	$date_2 = $fields[4][ 'unix' ]; 
	
	// If date 2 is earlier of the same as time 1
	if ( $date_2 <= $date_1 ) {

		
                // [ 'header' ] will display the error message above the form
                // [ 'footer' ] will display the error message under the form
		wpforms()->process->errors[ $form_data[ 'id' ] ][ 'header' ] = esc_html__( 'The pickup date should not be earlier than the order date.', 'plugin-domain' );
	}
	
}
add_action( 'wpforms_process', 'wpf_dev_compare_dates', 10, 3 );

If you’re not sure where or how to add custom snippets to your site, please check out this tutorial.

The way the snippet works is it will only execute on the form ID 731, then it will look for the Date field ID of 3 and the Date field ID of 4 and assign those to the variables $date_1 and $date_2 so that it can check if $date_2 is less than or equal to $date_1, if it is it will display an error above the second Date field showing that this date can’t be earlier than the other.

the error message will appear above when the snippet to compare two dates fails

And that’s all you need to compare two dates inside the same form! Would you like to provide some functionality for an age restriction to your form as well? Check out our tutorial on How to Provide an Age Restriction on the Datepicker Form Field.

Action Reference: wpforms_process