Last active
February 23, 2023 01:27
-
-
Save remcotolsma/5884430 to your computer and use it in GitHub Desktop.
Gravity Forms calculate number days between 2 date fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
jQuery( document ).ready( function( $ ) { | |
var ms_one_day = 1000 * 60 * 60 * 24; | |
var form_id = '1'; | |
var date_format = 'dd-mm-yy'; | |
var field_date_start = $( '#input_' + form_id + '_1' ); | |
var field_date_end = $( '#input_' + form_id + '_2' ); | |
var field_number_days = $( '#input_' + form_id + '_16' ); | |
var update_number_days = function() { | |
var value_date_start = field_date_start.val(); | |
var value_date_end = field_date_end.val(); | |
var date_start = $.datepicker.parseDate( date_format, value_date_start ); | |
var date_end = $.datepicker.parseDate( date_format, value_date_end ); | |
if ( date_start && date_end ) { | |
// Convert both dates to milliseconds | |
var ms_date_start = date_start.getTime(); | |
var ms_date_end = date_end.getTime(); | |
// Calculate the difference in milliseconds | |
var ms_difference = Math.abs( ms_date_start - ms_date_end ); | |
// Convert back to days and return | |
var number_days = Math.round( ( ms_difference + ms_one_day ) / ms_one_day ); | |
if ( $.isNumeric( number_days ) ) { | |
field_number_days.val( number_days ); | |
field_number_days.trigger( 'change' ); | |
} | |
} | |
}; | |
field_date_start.change( update_number_days ); | |
field_date_end.change( update_number_days ); | |
field_number_days.prop( 'readonly', true ); | |
update_number_days(); | |
} ); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment