How to Compare Two Time Fields in a Form


Are you interested in comparing two Time fields within your form and capturing the calculated difference in your entry? Look no further! This tutorial is tailor-made for you. We’ll guide you through the process of configuring your form and provide you with the necessary PHP snippet to seamlessly implement this functionality on your site.

Creating the form

To get started, let’s create a new form and configure our fields. In this guide, we’ll be designing a form specifically for reserving party rooms. Our snippet will utilize a Hidden Field to automatically calculate and append the total reserved hours to the entry. This feature is particularly useful for the accounting team, providing a straightforward overview for invoicing.

If you’re unfamiliar with creating forms, you can refer to this documentation for assistance.

In our form setup, we’ll include standard fields such as Name, Email, Address, and Phone. Additionally, we’ll incorporate a Dropdown field for room selection, a Date field for the reservation date, two Time fields for specifying the start and end times of the reservation, and finally, a concluding Hidden Field to store the calculated total hours using our snippet.

begin by creating your form and adding your fields

Adding the snippet

Next, we’re going to add the snippet to our site. If you’re not sure where or how to add snippets, please check out this tutorial.

 * Compare two time fields in a form
 * @link

function wpf_wpforms_update_total_field( $fields, $entry, $form_data ) {

	// Only run on my form with ID = 731
	if( 731 != $form_data[ 'id' ] ){
        return $fields;
    // Field ID 37 is the first time field of the form
    $start_time = strtotime( $fields[37][ 'value' ] );
    // Field ID 38 is the second time field of the form
    $finishing_time = strtotime( $fields[38][ 'value'] );
    // Field ID 41 is the hidden field that will calculate the difference
    // between the two time fields and store the hours inside a hidden field of the entry
	$fields[41][ 'value' ] = round(abs($finishing_time  - $start_time)/ 3600,2) . __( ' Hours', 'text-domain');

	return $fields;

add_filter( 'wpforms_process_filter', 'wpf_wpforms_update_total_field', 10, 3 );

This snippet will only run on the form ID 731. It will look at the two Time fields of the form, which are the IDs 37 and 38. Using the round function, it will calculate the difference between the two times and store the difference inside the Hidden Field

You’ll need to update the snippet to match the form and field IDs that you have in your form. If you need help in where to find these IDs, please check out this tutorial.

using this snippet you can now two time fields in a form

Would you like to also compare two dates? Take a look at our tutorial on How to Compare Two Dates in the Same Form.

Action Reference: wpforms_process