1. Home
  2. Knowledge Base
  3. WooCommerce Product Add-Ons Ultimate
  4. How to get the number of days difference between two dates
  1. Home
  2. Knowledge Base
  3. How To Guides
  4. How to get the number of days difference between two dates

How to get the number of days difference between two dates

Sometimes you might want to get the difference in days between two dates. WooCommerce Product Add-Ons Ultimate allows you to add date picker fields to your product pages. In this article, we’ll look at how to return the number of days difference between two dates entered by the user.

Get the difference between two dates

The first step is to create your fields:

  • Create two date fields, one for the start date and one for the end date
  • Then, create a number field. We’ll use this field to store the difference between the two dates
  • Make a note of the ID of each field

Next, you need to add the following snippet:

  • Here’s how to add the snippet
  • Once you’ve added the snippet, update the different field IDs at the top of the script with the IDs of your own fields

Publish the product and the difference in days will be displayed in the number field. Note that the number field is made readonly to prevent users from updating its value manually.

<?php
/**
* Update the three IDs below with your own field IDs
*/
function demo_get_start_date_field_id() {
return 1245; // The ID of the date field for the start date
}
function demo_get_end_date_field_id() {
return 1246; // The ID of the date field for the end date
}
function demo_get_result_field_id() {
return 1247; // The ID of the number field for the difference
}
function demo_date_difference() {
?>
<script>
( function( $ ) {
var date_difference = {
init: function() {
var result_field_id = <?php echo demo_get_result_field_id(); ?>;
$( '.pewc-number-field-' + result_field_id ).attr( 'readonly', true );
$( 'body' ).on( 'change update','.pewc-date-field', this.check_difference );
},
check_difference: function() {
// pewc-date-field-1246
var start_field_id = <?php echo demo_get_start_date_field_id(); ?>;
var end_field_id = <?php echo demo_get_end_date_field_id(); ?>;
var start_date = $( '.pewc-date-field-' + start_field_id ).val();
var end_date = $( '.pewc-date-field-' + end_field_id ).val();
if( start_date && end_date ) {
start_date = new Date( start_date );
end_date = new Date( end_date );
diff_time = Math.abs( end_date - start_date );
diff_days = Math.floor( diff_time / ( 1000 * 60 * 60 * 24 ) );
$( '.pewc-number-field-' + <?php echo demo_get_result_field_id(); ?> ).val( diff_days );
}
}
}
date_difference.init();
})( jQuery );
</script>
<?php
}
add_action( 'wp_footer', 'demo_date_difference' );

Was this article helpful?

Related Articles