Gravity Wiz

Magically enhanced tutorials, snippets and plugins for Gravity Forms!

  • Gravity Perks
    • Gravity Perks
    • Tutorials & Snippets
    • About
  • Support
    • Documentation
    • Support
    • Account

Calculate Number of Days Between Two Dates

Calculate the number of days between two given date fields and populate this number into a field on the form.

Last updated October 22, 2019 | Written by David Smith 387 Comments

  • February 10, 2015: Fixed issue where non-US date formats were not working as expected. Added link on demo to alternate version.

  • September 17, 2014: Fixed issue with newer versions of jQuery UI Datepicker where "change" event was not fired when a date was selected and day count was not calculated.

  • March 15, 2013: Updated to fix issue when conditional logic was used on the form.

  • March 3, 2013: Updated to fix issue where "include_end_date" option was not working and added better support for different date formats.

  • March 2, 2013: Updated to support applying to multiple sets of date fields on the same form. Also updated to fix issue where functionality did not run when form was returned due to validation error.

Show All Updates

Stop! There's a better way.

This snippet is available as a plugin with Gravity Perks, a suite of over 33 premium Gravity Forms plugins!

  • View the Plugin
  • Buy Gravity Perks
View DemoShow CodeDownload Code
<?php
/**
* Gravity Wiz // Calculate Number of Days Between Two Gravity Form Date Fields
*
* Allows you to calculated the number of days between two Gravity Form date fields and populate that number into a
* field on your Gravity Form.
*
* @version 1.1
* @author David Smith <david@gravitywiz.com>
* @license GPL-2.0+
* @link http://gravitywiz.com/calculate-number-of-days-between-two-dates/
* @copyright 2013 Gravity Wiz
*/
class GWDayCount {
private static $script_output;
function __construct( $args ) {
extract( wp_parse_args( $args, array(
'form_id' => false,
'start_field_id' => false,
'end_field_id' => false,
'count_field_id' => false,
'include_end_date' => true,
) ) );
$this->form_id = $form_id;
$this->start_field_id = $start_field_id;
$this->end_field_id = $end_field_id;
$this->count_field_id = $count_field_id;
$this->count_adjust = $include_end_date ? 1 : 0;
add_filter( "gform_pre_render_{$form_id}", array( &$this, 'load_form_script') );
add_action( "gform_pre_submission_{$form_id}", array( &$this, 'override_submitted_value') );
}
function load_form_script( $form ) {
// workaround to make this work for < 1.7
$this->form = $form;
add_filter( 'gform_init_scripts_footer', array( &$this, 'add_init_script' ) );
if( self::$script_output )
return $form;
?>
<script type="text/javascript">
(function($){
window.gwdc = function( options ) {
this.options = options;
this.startDateInput = $( '#input_' + this.options.formId + '_' + this.options.startFieldId );
this.endDateInput = $( '#input_' + this.options.formId + '_' + this.options.endFieldId );
this.countInput = $( '#input_' + this.options.formId + '_' + this.options.countFieldId );
this.init = function() {
var gwdc = this;
// add data for "format" for parsing date
gwdc.startDateInput.data( 'format', this.options.startDateFormat );
gwdc.endDateInput.data( 'format', this.options.endDateFormat );
gwdc.populateDayCount();
gwdc.startDateInput.change( function() {
gwdc.populateDayCount();
} );
gwdc.endDateInput.change( function() {
gwdc.populateDayCount();
} );
$( '#ui-datepicker-div' ).hide();
}
this.getDayCount = function() {
var startDate = this.parseDate( this.startDateInput.val(), this.startDateInput.data('format') )
var endDate = this.parseDate( this.endDateInput.val(), this.endDateInput.data('format') );
var dayCount = 0;
if( !this.isValidDate( startDate ) || !this.isValidDate( endDate ) )
return '';
if( startDate > endDate ) {
return 0;
} else {
var diff = endDate - startDate;
dayCount = diff / ( 60 * 60 * 24 * 1000 ); // secs * mins * hours * milliseconds
dayCount = Math.round( dayCount ) + this.options.countAdjust;
return dayCount;
}
}
this.parseDate = function( value, format ) {
if( !value )
return false;
format = format.split('_');
var dateFormat = format[0];
var separators = { slash: '/', dash: '-', dot: '.' };
var separator = format.length > 1 ? separators[format[1]] : separators.slash;
var dateArr = value.split(separator);
switch( dateFormat ) {
case 'mdy':
return new Date( dateArr[2], dateArr[0] - 1, dateArr[1] );
case 'dmy':
return new Date( dateArr[2], dateArr[1] - 1, dateArr[0] );
case 'ymd':
return new Date( dateArr[0], dateArr[1] - 1, dateArr[2] );
}
return false;
}
this.populateDayCount = function() {
this.countInput.val( this.getDayCount() ).change();
}
this.isValidDate = function( date ) {
return !isNaN( Date.parse( date ) );
}
this.init();
}
})(jQuery);
</script>
<?php
self::$script_output = true;
return $form;
}
function add_init_script( $return ) {
$start_field_format = false;
$end_field_format = false;
foreach( $this->form['fields'] as &$field ) {
if( $field['id'] == $this->start_field_id )
$start_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy';
if( $field['id'] == $this->end_field_id )
$end_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy';
}
$script = "new gwdc({
formId: {$this->form['id']},
startFieldId: {$this->start_field_id},
startDateFormat: '$start_field_format',
endFieldId: {$this->end_field_id},
endDateFormat: '$end_field_format',
countFieldId: {$this->count_field_id},
countAdjust: {$this->count_adjust}
});";
$slug = implode( '_', array( 'gw_display_count', $this->start_field_id, $this->end_field_id, $this->count_field_id ) );
GFFormDisplay::add_init_script( $this->form['id'], $slug, GFFormDisplay::ON_PAGE_RENDER, $script );
// remove filter so init script is not output on subsequent forms
remove_filter( 'gform_init_scripts_footer', array( &$this, 'add_init_script' ) );
return $return;
}
function override_submitted_value( $form ) {
$start_date = false;
$end_date = false;
foreach( $form['fields'] as &$field ) {
if( $field['id'] == $this->start_field_id )
$start_date = self::parse_field_date( $field );
if( $field['id'] == $this->end_field_id )
$end_date = self::parse_field_date( $field );
}
if( $start_date > $end_date ) {
$day_count = 0;
} else {
$diff = $end_date - $start_date;
$day_count = $diff / ( 60 * 60 * 24 ); // secs * mins * hours
$day_count = round( $day_count ) + $this->count_adjust;
}
$_POST["input_{$this->count_field_id}"] = $day_count;
}
static function parse_field_date( $field ) {
$date_value = rgpost("input_{$field['id']}");
$date_format = empty( $field['dateFormat'] ) ? 'mdy' : esc_attr( $field['dateFormat'] );
$date_info = GFCommon::parse_date( $date_value, $date_format );
if( empty( $date_info ) )
return false;
return strtotime( "{$date_info['year']}-{$date_info['month']}-{$date_info['day']}" );
}
}
# Configuration
new GWDayCount( array(
'form_id' => 16,
'start_field_id' => 1,
'end_field_id' => 2,
'count_field_id' => 4
) );
view raw gw-gravity-forms-day-count.php hosted with ❤ by GitHub

Have you ever needed to calculate the number of days between two given date fields? Here’s a scenario for consideration.

Let’s say you have a Gravity Form set up to register users for a multi-day event. The user is able to select a start date and end date that they will be attending the event. For each day of attendance they must pay an attendance fee of $10. How can we calculate the total price they should pay for registration?

This snippet will allow to calculate the number of days between two date fields and then populate the calculated number of days into another field. This is beneficial because with this calculated number of days now available as a field value, we can use Gravity Forms’ Calculation Product to correctly calculate the registration fee based on the selected dates.

How do I install this snippet?

Easy peasy. Just copy and paste the code above into your theme's functions.php file.

How do I use this functionality?

To use this snippet’s functionality just go directly below the snippet and instantiate the GWDayCount() class. Instantiate is a big word but all it means is that you’ll be creating a new “instance” of the GWDayCount() class with a set of parameters (aka options) for that specific instance.

Standard Usage

new GWDayCount( array(
'form_id' => 9,
'start_field_id' => 1,
'end_field_id' => 2,
'count_field_id' => 3
) );

Count “Nights” Only
End date is not included in the day count so you are essentially counting the number of “nights” between the two dates.

new GWDayCount( array(
'form_id' => 9,
'start_field_id' => 1,
'end_field_id' => 2,
'count_field_id' => 3,
'include_end_date' => false
) );

Once you instantiated the class you are finished! If you would like to have this functionality on multiple forms then just create a new instance of the class and fill in the parameters for the new form. That’s it!

Parameter Details

  • form_id: The form ID of the form you would like to apply this functionality to.
  • start_field_id: The ID of the date field that will contain the start date. This field must be a date field and the parameter only holds a single field.
  • end_field_id: This parameter holds the ID of the date field that will contain the forms end date. This field, like the start_field_id field, must be a date field and only holds a single field ID.
  • count_field_id: This parameter holds the ID of the field that will be populated with the calculated number of days between the start date and end date.
  • include_end_date: Defaults to true. Set to this false if you would like to count only “nights” where the start date would be the check-in date and the end date would be the check-out date.

Points of Note

  • This is currently only setup to work with “Date Picker” date fields. Let me know if you need this with other types of date fields in the comments.

Did this resource help you do something awesome with Gravity Forms? Then you'll absolutely love Gravity Perks; a suite of 32+ essential add-ons for Gravity Forms with support you can count on.

  • View All Perks
  • Buy Gravity Perks

Filed Under: Snippets

Comments

  1. James says

    December 10, 2020 at 6:59 pm

    how to calculate the days except the weekends? is it possible? thanks

    Reply
    • Ryan Donovan says

      December 11, 2020 at 1:41 am

      Hi Ruairi, Our Date Time Calculator supports calculating weekdays and weekendDays.

  2. Alex Abrams says

    November 1, 2019 at 9:18 am

    Hi David, I’ve installed the ‘Calculate Number of Days Between Two Gravity Form Date Fields’ snippet and it was working wonderfully in Gravity Forms. However, we’re using Gravity Views and it stops the ‘Edit Entry’ screen from rendering and I don’t understand why. Have you run into this issue with your ‘GravityWiz’ plugin? All I’m doing is finding the days difference between the current date and the user’s data of birth. I’m using your ‘GW_Populate_Date’ snippet prior to the aforementioned snippet to populate the Current date and this appears to work correctly.

    Reply
    • David Smith says

      November 4, 2019 at 7:34 pm

      Hi Alex, GravityView alters some of the core functionality of Gravity Forms when it renders forms in the Edit Screen. Unfortunately, we can only guarantee that our snippets will work with Gravity Forms proper. We have so many!

      Fortunately, this snippet has a plugin version that will work with GravityView. It’s called Date Time Calculator and it’s even easier to use than the snippet. If you give a shot, I’d love any feedback you have. 🙂

  3. naranili says

    October 21, 2019 at 1:57 pm

    Does this also work with a date-Dropdown instead of a datepicker ?

    Reply
    • David Smith says

      November 4, 2019 at 3:44 pm

      The snippet version does not; however, the perk version, Gravity Forms Date Time Calculator, does!

  4. RHYS COMLEY says

    October 17, 2019 at 11:34 pm

    Hello, how can i only return results greater than 5, i.e i only want to calculate days and return value greater than 5.

    i.e Start date 1st end date 7th returned value = 2 i.e Start Date 1st end date 5th returned value = 0 i.e Start Date 1st end date 3rd returned value =0

    i think i need to do a if statement, return value if greater than 5-5?

    Reply
    • David Smith says

      November 4, 2019 at 9:58 am

      Hm, you could have two calculation fields with the same formula and then use conditional logic to show/hide the second calculation field if the value was greater (or less than) 5. Then you would only use the second calculation field’s value.

  5. Laras says

    September 18, 2019 at 10:09 pm

    what if the opposite. I have a member data that entered the x date with a validity period for y months. What date will the membership end. What plugins or GW solutions are suitable for the solution?

    Reply
    • David Smith says

      September 19, 2019 at 7:24 am

      Hi Laras, it sounds like you’re looking for: https://gravitywiz.com/populate-dates-gravity-form-fields/

  6. ET says

    September 8, 2019 at 9:38 pm

    I’m not a programmer, but I manage to insert the code to my child theme functions.php, and had modify the Form ID and Field ID as accordingly

    But after that I do not know what to do.

    On My Gravity Form itself I had 1. Start Date (Date Field) 2. End Date (Date Field 3. Duration (Text Field)

    at the Duration Field I checked “allow field to be populated dynamically” then enter the parameter field as “GWDayCount”

    Am I doing it correctly?

    Reply
    • David Smith says

      September 9, 2019 at 7:21 am

      Hi ET, it sounds like you have field types right but this doesn’t use dynamic population. If you’ve configured the snippet correctly, it should “just work” after you’ve replaced the field IDs with your own. More help here: https://gravitywiz.com/documentation/snippet-troubleshooting/

  7. Ido says

    July 11, 2019 at 8:29 am

    thanks! works great – but I have the same question as Robert: I want to calculate years and not days. How do I do that? Basically I’ve set the “start_field_id” to a “birth date” field, and the “end_field_id” to a date field with default value of “{date_mdy}” – so I get the calculation between the birthday and today – but i get it in days, whereas i want it in years. is this done via the Gravity Forms Date Time Calculator perk? and if so – how and where do i get this perk? it’s not on the perks list. thx!

    Reply
    • David Smith says

      July 11, 2019 at 10:01 am

      You could always divide that number by 365. Results may not be 100% accurate but they’ll be pretty close. The Gravity Forms Date Time Calculator perk handles this a little more robustly. This early access perk is available by request to any Gravity Perks customer. ?

  8. Robert says

    July 3, 2019 at 2:48 pm

    Hi David, thanks for this info. Could I use this code to calculate age (today minus date of birth)?

    Thanks.

    Reply
    • David Smith says

      July 10, 2019 at 8:45 am

      Sure. Or if you’re a Gravity Perks customer, just request the Gravity Forms Date Time Calculator perk which includes an :age modifier for calculating this with a single date field.

  9. Peter Muir says

    July 1, 2019 at 9:24 am

    So this is a bit of an odd one… it works perfectly until I enable Partial Entries. Once I do that the window.gwdc script is moved to before the opening html tag.

    Reply
    • David Smith says

      July 1, 2019 at 6:24 pm

      Hi Peter, this is unlikely something we will fix in the snippet-version of this; however, we do have an early-access perk called GP Date Time Calculator that offers a far superior solution. It’s available to any Gravity Perks customer by request.

« Older Comments

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Categories

  • How To (64)
  • News (21)
  • Plugins (14)
  • Releases (7)
  • Resource (3)
  • Snippets (58)
  • Tutorials (57)
  • Updates (104)

Recent Posts

  • How to Send a Follow-Up and Pre-Fill Information
  • How to Update Posts with Gravity Forms
  • Gravity Wiz Weekly #104
  • The Complete Guide to Using Gravity Forms With Zapier
  • Gravity Wiz Weekly #103

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Copyright © 2021 · Powered by WordPress · Gravity Wiz LLC

  • Support
  • Affiliates
  • About
  • Sitemap
  • Gravity Perks
    â–¼
    • Gravity Perks
    • Tutorials & Snippets
    • About
  • Support
    â–¼
    • Documentation
    • Support
    • Account