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.
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.
Stop! There's a better way.
This snippet is available as a plugin with Gravity Perks, a suite of over 46 premium Gravity Forms plugins!
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
) );
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.
Hi got error while adding code in function.php.
Your PHP code changes were rolled back due to an error on line 191 of file wp-content/themes/astra/functions.php. Please fix and try saving again.
syntax error, unexpected token “<“, expecting end of file
Hi Amit,
The error message is because of how you added the code to your website. Check this documentation on how to install a snippet.
Best,
Hi, Great snippet and works great. Am just having an issue whereby the calculated days are not showing correctly in the notification emails sent. On screen all is 100% but when I receive the notification, the days are always set to 1. Any ideas?
Hi Ivo,
I’m not sure why that is happening. We’ll need to dig into this further to know what’s happening. I’ll contact you via email to request additional information.
Best,
Ok, thanks. Look forward to your email.
Hi Samuel, You manage to look into the issue or perhaps you can send me an email so I can you more information?
Hi Ivo,
I sent you an email on 28th June 2023, requesting you to send us an export of the form. I guess you didn’t receive it. Since you have an active Gravity Perks license, can you submit a support ticket with us via our support form and attach an export of the form.
Best,
Hi Samuel,
Found your email on the server and have replied.
Hi David, a great snippet of code. Thank you.
I would like to know if it is possible, to calculate only the first 7 days of the reservation and not to calculate the rest days as an additional cost. Because we want to charge only for the first 7 days and the rest to be free, Thank you.
Hey Mat, glad you’re enjoying the snippet! Unfortunately, it doesn’t support setting a “max” value.
This would be possible using Date Time Calculator to handle the date calculation and Advanced Calculations
min
method which would return the lowest number (e.g. 7 or the actual number of days calculated).First, sorry for my english.
I’m trying this code, but it doesn’t work. I’ve added the code to functions.php (I have also tried with the snippets plugin) and filled in the form data in the function, but not show anything on view.
Fecha inicio (date field) ID: 1 Fecha fin (date field) ID: 2 Diferencia de dias (number field) ID: 3 Form: ID 5
Configuration
new GWDayCount( array( ‘form_id’ => 5, ‘start_field_id’ => 1, ‘end_field_id’ => 2, ‘count_field_id’ => 3 ) );
But not show anymore:
http://clinicacamposfisioterapia.com/view/diferencia-fechas/
Can you help me, please?
Hi Alexis,
The snippet works with Gravity Forms and not GravityView. If you want a solution that works in GravityView, then you can take try our GP Date Time Calculator Perk.
Best,
hi,
I used this code to check address history if it is up to 5 years and when I created the form it worked, but if add the form to the Nested form the calculation stops working. How do I use it with a nested form to calculate and validate address history?
Hi Ezex,
We’ll need to take a closer look at your setup to determine what’s wrong. If you have an active Gravity Perks License, you can get in touch with us via our support form with additional information. You may also want to try using our GP Date Time Calculator Perk for this functionality.
Best
Hi sir, Im all new to all wordpress and php stuffs. i need your help.
i tried to use this and it doesn’t work at all for me. I copied the 2000 line code without any error following your guide. then i copied your new GWDayCount for the night count
new GWDayCount( array( ‘form_id’ => 60, ‘start_field_id’ => 14, ‘end_field_id’ => 13, ‘count_field_id’ => 62, ‘include_end_date’ => false ) );
i updated the functions.php and no error so far. i even rebooted the whole wordpress and server to be sure everything would work. This is the step i’ve done.
Hi Frederic,
If the setup is correct it should work as expected. You can try using Code Snippets plugin instead of modifying the functions file.
If you have a Gravity Forms License, you can get in touch with us via our support form with an export of your form and any additional information so we can assist you further.
Best,
Hi, when putting this code into FUNCTIONS.PHP I get the following error:
Your PHP code changes were rolled back due to an error on line 34 of file wp-content/themes/uncode/functions.php. Please fix and try saving again. Uncaught Error: Class ‘GWDayCount’ not found in wp-content/themes/uncode/functions.php:34 Stack trace:
0 wp-settings.php(546): include()
1 wp-config.php(98): require_once(‘/home/sq49dtyo/…’)
2 wp-load.php(50): require_once(‘/home/sq49dtyo/…’)
3 wp-admin/admin.php(34): require_once(‘/home/sq49dtyo/…’)
4 wp-admin/theme-editor.php(10): require_once(‘/home/sq49dtyo/…’)
5 {main}
thrown
Hi Ad,
Based on the error message, it appears you’ve only added the configuration of the snippet and not the actual Class. Here is a link to the complete snippet.
Best,
Is there any way to add 14 days to a specific date, but then return the new calculated date in a specific format? For example, date in one field is 6/1/2021 and I want to add 14 days but then have it return “June 15, 2021”
Hi Mikhail,
We have a snippet you can use to modify and populate a Date field with the modified date. Here is the documentation to the snippet with details on the various options available. I would guess a configuration like this would work for you.
Best,
It seems to be working in functions.php file. However when I place it with my other snippets in a separate plugin, it brakes the website. Can there be something done?
Hi Vitaly,
Since it works when placed in the function.php file, I don’t think there is an issue with the code. It could be with the way you’re inserting the snippet in the snippet plugin. If you have a Gravity Perks license, you can get in touch with us via our support form so we can assist you further. That said, here is documentation on how to install a snippet, to see if it helps.
Best,
Thank you for your time Samuel. Yes, the snippet works but, as I said, it breaks the website.
Cheers,
Hi Vitaly,
I’m unable to recreate this issue when I test it with the Code Snippets plugin.
We recommend purchasing the Perk version of this snippet. Not only does it offer more features and ease of use, it also includes support.
how to calculate the days except the weekends? is it possible? thanks
Hi Ruairi, Our Date Time Calculator supports calculating weekdays and weekendDays.
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.
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. 🙂
Does this also work with a date-Dropdown instead of a datepicker ?
The snippet version does not; however, the perk version, Gravity Forms Date Time Calculator, does!
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?
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.
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?
Hi Laras, it sounds like you’re looking for: https://gravitywiz.com/populate-dates-gravity-form-fields/
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?
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/
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!
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. ?
Hi David, thanks for this info. Could I use this code to calculate age (today minus date of birth)?
Thanks.
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.
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.
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.
Done installing the snippet. How to use this? Thank you in advance :)
Got already on how to use the snippet. But how can I use it also on my other form?
This will help: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Hi, this works great. Do you have any suggestions on changing the date for datepicker 2 if datepicker one becomes the same or greater than datepicker2?
Gravity forms article section: 4. Datepicker 1 + 1 month becomes minDate for datepicker 2 suggests how to make date picker 1 the minimum for datepicker 2 but this breaks the counter if say you set the two date pickers and then move datepicker 1 backwards because datepicker 2 will change. Here’s the article for reference.
https://docs.gravityforms.com/gform_datepicker_options_pre_init/#3-datepicker-1-becomes-mindate-for-datepicker-2
Disregard, I was able to solve this.
Hi,
we are getting the following error when trying to install the snippet in the child theme’s function.php:
Uncaught Error: Class ‘GWDayCount’ not found in wp-content/themes/oceanwp-child-theme-master/functions.php:32 Stack trace:
0 wp-settings.php(499): include()
1 wp-config.php(90): require_once(‘/homepages/26/d…’)
2 wp-load.php(37): require_once(‘/homepages/26/d…’)
3 wp-admin/admin.php(34): require_once(‘/homepages/26/d…’)
4 wp-admin/theme-editor.php(10): require_once(‘/homepages/26/d…’)
5 {main}
thrown
Any idea how to troubleshoot this one?
Hi Christoph, give these troubleshooting steps a try: https://gravitywiz.com/documentation/snippet-troubleshooting/ My instinct is that you’ve installed the configuration part of the snippet but not the full snippet. You’ll need both.
Sorry, you were right. My bad! Thanks for your help.
Glad to help. ?
Hi
I did this, all looking fine for me. My next step is, that I have prices for a service, and they vary depend of the amount of days.
Any idea, how is the best way to calculate and get a number, where the amount per days is vary?
Regards,
Simon
Hi Simon, it really depends on your pricing logic. If it’s just adjusting the cost by a static amount as the number of days increases, our Gravity Forms Conditional Pricing perk might be a good fit.
Hi, how do i add to two separate forms? I attempted to just add another line of this text :
“new GWDayCount( array( ‘form_id’ => 5, ‘start_field_id’ => 4, ‘end_field_id’ => 8, ‘count_field_id’ => 31, ‘include_end_date’ => false ) );”
Changing the form id, but it isn’t working on the new form. Am I doing something wrong?
Hi this now gives a pluggable error when implemented in functions.php file. Any chance you have a fix for this?
This is typically an issue installing the snippet. Try these steps: https://gravitywiz.com/documentation/snippet-troubleshooting/
Actually, it was being caused because of the tags within the code. I replaced it with an enqueue script function and called a separate file with the script.
Hi Esther, this might also be helpful: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
What type of field do I need to use to make this work? I tried with a number field but it is not populating.
FYI, I purchased the 1 perk package (conditional dates) if that has anything to do with it.
Actually, sorry. It is working with the number field. I forgot to clear my cache. Sorry!
Glad you were able to get this working. ?
I want to know if this works with what im trying to do is.
when a customer select a start date and end date it checks the month if its from january to january then it charges $80 if the date is between january to february then is should charge 80+70 and so on.
would I be able to do something like this with this ?
Does it actually matter which months or are you just attempting to calculate the number of months and then the first month is $80, second month is $70, third month is $60, and so on?
Hi, I’m stuck at this step
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!
What does it mean to instantiate the class?
Hi Ivonne, 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. See the “Standard Usage” usage example.Hi,
The snippet works great. But the jQuery script (i.e. window.gwdc) gets added at top of the HTML before DOCTYPE when the gravity form is loaded in a popup using any plugin which throws jQuery not defined error. Do you have any solution for that?
Thanks, Mou
Hi Mou, we have made some improvements to how we load scripts in snippets but they have not been implemented here. If you have any PHP experience, here’s an example of how the scripts should be enqueued: http://snippi.com/s/1dj9jke This snippet is in the queue for an update. No definite ETA.
Is it possible to calculate the range between two dates and recalculate the subtotal at checkout page? Yes, we are trying to use it as a simple booking system.
This snippet would allow you to calculate the number of days between two dates. You could use that in a Product calculation field to calculate a product price based on that number.
Fatal error: Call to undefined function wp_parse_args() in E:\xampp\htdocs\Funeral-Homes-Portal\celi.php on line 20
Hi ging, it sounds like you installed the snippet in the wrong file. Try this: https://gravitywiz.com/documentation/snippet-troubleshooting/
Is there anyway to calculate the range between two dates excluding a certain day such as sundays??
Hi Ruairi, Date Time Calculator supports calculating weekdays and weekendDays between two dates but does not support calculating the number of a specific day.
Hi, is there a documentation on how to use the GP Date Time Calculator?
Hi Shane, if you’re a Gravity Perks user we can a) send you an early-access copy of Date Time Calculator and b) provide a video overview of how it works. Drop us a line via support.
Hi, How do I use this? Not sure I understand the below. Is there an example?
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.
Not understanding the above.
This might help: https://gravitywiz.com/documentation/snippet-troubleshooting/
Dear David
Thanks for the code!
” Uncaught Error: Class ‘GWDayCount’ not found in wp-content/themes/oceanwp-child/functions.php:25 “
Best Tal
Hi Tal, we do have a plugin version of this functionality called Date Time Calculator that is available by request to Gravity Perks users. If you’d prefer to use this snippet, you might find these troubleshooting tips helpful: https://gravitywiz.com/documentation/snippet-troubleshooting/
Thanks David Your link helped me see where I had a mistake. But, I now have another problem implementing it… Is it possible to pay for this days ability only? (we really don’t need the rest of the really awesome ‘perks pack’, and also trying to keep the website lean as possible). Tal
Hi Tal, it sounds like you need the Basic package which gives you access to one perk on one site. You never have to worry about leanness with Gravity Perks because you only install the perks you need.
Well… Just bought it :-) Going to look for the instructions. Thanks Tal
Awesome! Drop us a line via support and we’ll get you the latest version of Date Time Calculator. ?
David, I’d like to use this snippet to calculate the difference between two dates: – today – start of an event date I will not use date picker fields as the second date is set and will (in a later form update) be populated using your populate anything perk as it is taken from a clan calendar plugin. Do you have a version of this snippet that works with regular date fields in this manner?
Ignore the above request. It seems that using the date picker format makes it easier to populate the field dynamically as one input is provided (as opposed different year, month and day fields when the date type is selected). Only weird thing is that apparently a separate filter setting is required to make a datepicker actually read-only when using the relevant perk.
Yes, readonly only applies to the manual user input (just like in your browser) by default. Javascript is able to interact with inputs regardless of the readonly attribute so an additional filter is required if you want to disable the datepicker.
David, okay thanks for the explanation. I’ll drop the relevant code in my snippets plugin items (nice alternative for functions.php which gets overwritten on theme update or having to struggle with child themes tec.)
David,
What I want to do is a little complex. Or at least it is for me. I am, sadly, not a coder.
I want to notify our clients as to when their stuff will be ready. I want to take today’s date and add 21 days to it.
I want to have something at the bottom of the form, before they submit, that says “Your documents will be created on or before 3_weeks_From_Today”
Ideally, I would have a single radio button or checkbox that says “I understand my documents will be ready on variable_date.”
But I realize that’s a probably a tall order!
Any feedback is greatly appreciated, even if its: “Hire a coder!”
Thank you in advance.
Hi Michael, you could use our Populate Dates snippet to populate the 3-weeks-from-today Date into a field and then use our new Populate Anything perk to pull that date into a Checkbox label or HTML Field content.
For my project, I needed to modify the code slightly because the javascript being output in this function “function load_form_script( $form )” was preventing my redirect at the end of my form.
(I’m using Gravity Forms to generate a custom product and add it to the cart – without ajax – and then redirecting to the cart upon completion of the form).
The solution was to remove the entire chunk of javascript (line 50 to 142) and put it inside the form in a HTML block.
I also cleaned up the PHP by removing the “self::$script_output = true;” both above and below where the javascript was, and not more “can’t modify headers” error after submitting my form.
Hope this helps others who run into this issue.
When I add the code into my functions file, WordPress get the white screen of dead. Are there some changes needed for WP5?
Hi Robbin, this might help: https://gravitywiz.com/documentation/snippet-troubleshooting/
Thanks for this solution.
I’m trying to get a calculation of age (of a person) from date of birth working. It calculates it in days, which is not ideal ;)
At the moment, I then use a hidden field with a current date, and date of the birth date picker. Then I use a field with a calculation a formula (age-in-days)/365.25, but this is not quite accurate.
Any chance you could guide me through this?
Many thanks in advance!
We recommend our GP Date Time Calculator early-access perk for this. It provides an “:age” modifier for any Date field so you can accurately calculate age. If you’re a Gravity Perks customer, drop us a line via the support form.
This script is just awesome, thanks for sharing it.
Glad we could help, Vikas. :)
Hello ive added the snippet to my functions.php file, i dont recieve any errors. it does not work. PLease assist.
Hi Darren, first place to start is here: https://gravitywiz.com/documentation/snippet-troubleshooting/ If that doesn’t work, we have an early access perk called GP Date Time Calculator available by request to Gravity Perks license holders that can handle this easily and requires no code.
Is it possible to exclude weekends from this count? and where possible public holidays?
This is possible with a special merge tag provided by our Early Access perk, GP Date Time Calculator. This perk is available by request to any Gravity Perks license holder.
Hi, this script works 100%! Thank you. I also just purchased the Date Limit perk. Have however run into a bit of a problem now as I need this to work with more than one date range, as I have multiple date ranges that are presented to the user based on their initial selections. Any chance you have a solution for that?
Hi Ivo, glad this snippet works for you. If you haven’t already, drop us a line via the support form and we’ll be happy to look into your other issue.
https://gravitywiz.com/support/
Thanks. I have submitted my request/issue to support.
Hi David, how can i call the GWDayCount function inside a form so that i dont need to do changes again and again in Functions.php , is there any way that i can use that call the class within the Form?
Hi Karim, if you’re looking for a UI, I would recommend our early access GP Date Time Calculator perk which makes doing this a breeze. If you’re interested, pick up a copy of Gravity Perks and drop us a line via support.
Dear David –
My client offers services. The rate for the service goes down with how the delivery time increases. For urgent service, in 4 hours, the rate is highest – then the rate tapers in 4 hour intervals as the delivery time chosen is furthened. Been through all your literature it seems.
Will your “GP Date Time Calculator” help me build something using SIMPLE gravity form date and time fields, with merge tags, that allows the customer to choose a date and time of delivery…subtracts the hidden field of the date/time of ordering the service, and based on simple conditional logic, given the number of hours, selects the appropriate EDD product?
This is all theoretically straight forward.
Thanks … and eager!
I don’t know how the EDD product integration works but you could certainly use GP Date Time Calculator to calculate the number of hours between a current time and a future time and then use conditional logic to show/hide fields based on that number.
Fatal error: Call to undefined function wp_parse_args(), any idea how to solve this problem? :D
Try these tips: https://gravitywiz.com/documentation/snippet-troubleshooting/ :)
Hi David, After I bought GP and got the Date Time Calculator from Mr. Jordan Smith, I tried the attached special shortcode and worked fine in the number field. However, the issue is when I submit the form I got only number 1 instead of the right calculation results.
Hi Salman, if you haven’t already, drop us a line via support. We’ll be happy to sort this out for you. :)
Hello David, the script is just awesome, but I have a weird issue on Yoast page-sitemap.xml.
in some way, the js loaded with the load_form_script function, is injected at the beginning of the page-sitemap.xml, breaking it.
URL: view-source:https://www.greenparkmadama.it/page-sitemap.xml
I really have no clue on how this can happen! Anyone can replicate this issue?
Hi Bluantinoo, we’re not able to provide support for 3rd party plugins with our snippets; however, if you’re a Gravity Perks customer, we’ll be happy to provide additional support via the support form. I would strongly recommend the GP Date Time Calculator for this functionality anyways. No touching code and the plugin is well supported.
Fantastic! Worked like a charm! Even was able to edit to allow for negative numbers as a result (needed to check for pre-sale deadline on form). Why GF doesn’t build in logic/calculations for dates is beyond me.
Good stuff, Joel!
Hi David, I installed the GP Date Time Calculator, but cannot see an option for the calculation in my form. Which field type do I need to use for the calculation? Thanks for your help.
Hi Sven, hit us up via support and we’ll get you squared away. :)
When I enter your code in my functions.php my site goes offline and I get code error 500
This might help, Soren: https://gravitywiz.com/documentation/snippet-troubleshooting/
that solved the problem thanks David :)
Using this snippet and adding the value to a ‘amount’ filed which is multiplied with the product field (booking/rental calculation) is working fine on the website, but when confimation emails are sent out, the calculated price is ALWAYS 0. When removing the data calculation, everything seems right again in the email? Any quess why?
I’m not able to recreate this issue. We have an early-access plugin that can handle this functionality called GP Date Time Calculator. Pick up a copy of Gravity Perks and drop us a line via support form if you’d like to take it for a spin.
Absolutly cannot get this to work. Told a client the site would be done last weekend
I confirmed that this snippet is working. If you’re looking for a codeless solution, we have an awesome early-access perk called GP Date Time Calculator which can make this task much easier. Pick up a copy of Gravity Perks and drop us a line via support and we’ll be happy to send you a copy. :)
I have added this code and all is working well when I use the form “preview” but when I load the form onto a page it is not showing the calendar drop down at all for selecting dates.
When I inspect element it is showing this error: Uncaught ReferenceError: jQuery is not defined
and also this: Uncaught ReferenceError: gwdc is not defined
Really appreciate any help you can give me :)
Hi Adrian, sounds like a theme/plugin conflict. I’d start here: https://docs.gravityforms.com/testing-for-a-themeplugin-conflict/
Hi david, after last wordpress updated I get this error when I click on button to confirm the form.
This error only with the forms that use this script…how to fix it?
Thank you!
This is the error:
Warning: Cannot modify header information – headers already sent by (output started at /home/myrecept/public_html/wp-content/themes/Divi-child/functions.php:65) in /home/myrecept/public_html/wp-includes/pluggable.php on line 1210
Drop us a line via support and we’ll be happy to take a look.
Hello. How to get the value of count-field in JS? For example, the code – var days = $jq(‘#input_7_4’).val(); don’t work.
Hm, that should work. Here is what I used to get it on the demo form (see top of article):
var days = jQuery( '#input_16_4' ).val();
.Can not get it working. I made a plugin from the code but the number of weeks is not working
Have a arrival field (id4) departure field (7) and want to use the weeks (field id 10) for calculating rent. form id=1
Hi Vince, hard to say what isn’t working but if you’re a Gravity Perks user, we have an early-access plugin called GP Date Time Calculator that makes calculations like this easy right in the form editor with any calculation-enabled field (no code required). Drop us a line via support.
Hi david, I bought your perks and I use this script but I have a question about it…I would use this with 2 or more gravity forms, how to add the second form in the follow code?
Thank you!
Hi Paolo, this will help: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Hi David,
Thank you for this nice snippet.
Can you please also advise how can we show a third field as a dropdown with list of number from 0 to the end number is equal to the difference between the two dates?
I have restricted the second date field to not give permission to user to select more than 60 days date based on the date entered in first date field.
Thanks, your help will be really appreciated.
Hi Sam, this is not readily possible out-of-the-box. You’d need to write some custom code to add those options dynamically any time the number of days changes. I don’t really have a walk-through for this one.
I got it working, however, how would I hide the number field? As you can see in the demo the number field is already displayed, I want it hidden until the dates are selected? How would I be able to accomplish the task you have in the demo.
Your help would be appreciated.
Hi Rawad, you can set the Visibility to Hidden (via the field settings) or you can use GF Conditional Logic Dates to only show the field if both Date fields have values.
Hello David,
Thank you for the quick response. I believe the JQuery date picker isn’t featured yet, meaning I can’t accomplish the task. I’m using the JQuery Datepicker fieldset.
I look forward to your response.
Hi Rawad, the Datepicker date type is supported.
Is there a way to use this snippet to calculate a persons age based on their date of birth input and the current date? I would want their current age to go into a field on the form so I can use it as a conditional rule for other fields.
Hey Sam, drop us a line via support and include this link:
https://gravitywiz.com/calculate-number-of-days-between-two-dates/comment-page-5/#comment-282519
We can provide you GP Date Time Calculator which supports calculating age via a Calculation field.
I added the code you provided to the function.php file and it crashed my site. I have the code listed below, Your help would be truly appreciated.
Hi Rawad, this will probably help: https://gravitywiz.com/documentation/snippet-troubleshooting/
can you explain me how to run this snippet im having some problem in this..
The article is written to explain how to use the snippet. Do you have a more specific question? If it’s about installation, this might help: https://gravitywiz.com/documentation/snippet-troubleshooting/
Hi David,
We would like to use this functionality for a calculation for Car Rental. There is a special rate for single days, weeks and full weekends. Can you adjust the plugin (we can pay for that) so it functions like this form: http://bit.ly/2nY9uPx ?
Thanks in forward!
Possibly, contact me here with a full list of specs and I’ll be happy to take a closer look: http://ounceoftalent.com/contact/
Hi, great snippet!
However, I think I’m messing something up. My form disappears when using the snippet as the CSS goes to “display: none;”. It works fine when displaying the form in a pop-up from pop-up maker. Changing the display to block makes the form visible but the calculations do not work.
The form: http://topsportacademy.com/camp-planner/
Thanks!
Hi Wessel, it looks like the actual JS script is not being included for some reason. We have a better solution for this with GP Date Time Calculator. It is available by request for Gravity Perks license holders.
I’m looking for a method to calculate the number of hours between 2 or 3 sets of times within a period. For example, creation of a time sheet.
Goal is to calculate: Advanced Field: Time (1) | Advanced Field: Time (2) | Advanced Field: Time (3) | Total Start Time End Time Break # of hours 8 AM 6PM 1 PM 9
What is the best way to go about doing this? I’ve noted a variety of links that could possible help get me there: (i.e.) https://github.com/soulseekah/gravityformstimesheet – But I need more clarification & guidance on what to do.
Can you help on this?
If the Time fields are separate fields and not part of a List field, you could use GP Date Time Calculator to calculate the time differences between each. It is available by request for Gravity Perks license holders.
Is there any way to make this work with https://nl.wordpress.org/plugins/gravity-forms-list-field-date-picker/ and have a calculation of days in between per row (with dates selected in that row)?
Possible but, as you probably guess, it’d require additional custom code to support.
Hi, First, thanks for this snippet! In a recent update of wordpress and/or gravity forms the datepicker on my form started using the date format from the site instead of the date format from the form.
Since the date format from the site was Month dd, yyyy (or F j, Y ) the difference between dates couldn’t be calculated, I assume because of the text in the format.
When I switched the date format for the site in the wordpress “Settings” to mm/dd/yyyy the dates in the form were able to be calculated. I contacted gravity forms and they said it was a snippet issue so now I’m contacting you. Any idea on why the date format of the site is overriding the date format of the form?
The site is using the latest version of wordpress and gravity forms. Also, I updated the code of the snippet to latest version sometime early last year.
I’d give you an example site but it’s a live site and it’s currently “fixed”. I would like to be able to use a different date format for the site than for the form tho. I currently can’t do that and have the form function properly with the calculate days snippet at the same time. If you can’t replicate the issue, I could set up a form on a test site to show you but I’d prefer to share the site address offline if possible.
Any help or advice is greatly appreciated.
Thanks in advance!
Hi Dubyajay, I confirmed this is working for non-US date formats. See the demo here: https://demos.gravitywiz.com/calculate-number-of-days-between-two-dates-non-us-date-format/ If you’re still having issues, I would pick up a copy of Gravity Perks and send us a request for GP Date Time Calculator which handles this functionality without code via the support form.
Thanks for your quick reply! My issue isn’t non-us date formats. It’s having one date format in the WordPress settings and a different format in the gravity form datepicker field. It is defaulting to the WordPress format. If I want wordpress to format as Month dd, yyyy and then have the gravity form datepicker field to be mm/dd/yyyy it defaults to Month dd, yyyy which cannot be calculated. Could you test that?
Hi Dubygay, the WordPress format should not be impacting your Date fields. Make sure you’re running the latest version of Gravity Forms.
Yes, I know it shouldn’t affect it but the only way I could get the calculate days snippet to work is to change the wordpress date format to match the one inthe form datepicker.
I’m running latest wordpress and gravity. I’ve been using this snippet for several years and it’s worked great. Something changed in either wordpress or gravity the last week or so to make the date in gravity misbehave.
I contacted gravity forms about this (I have a developers license) and they said it’s a gravity wiz issue. That’s why I’m contacting you.
I’m not able to recreate this issue. The demo site’s default date format does not match that of the field’s. Our recommendation is to pick up a copy of Gravity Perks and send us a request for GP Date Time Calculator which handles this functionality without code via the support form. We are better able to support our paid-for products.
Hi David, Thank you for posting this code! Now I read this I think maybe you can help me.
I see the GP Date Time Calculator demo, I just do not see how I can buy it. I will explain my situation: I have a car rental company and I use a form of Gravety Forms, A good product, but I can not do everything with it what I want.
I want to specify that I have a PickUp day and a DropOf day. 1. First, you can select a date that has already passed, that I can’t set the hours is not very important. I count each day from 09:00 to 08:30 next day, for 1 dag/ night. I saw that this was possible with “GP Date Time Calculator” Now next: I have different rates if they rent for one day than X amount cost per/day, At 2 to 4 days an X amount, at 4 to 7 days a x amount per/ day… you know what I mean.
We also rent loose products with it for the x amount of days, such as GPS, child seats and insurance. etc. Does the add-on support this option too?
It would be nice to have an option to set a minimum number of days required: for example, you can select at least for 2 days?
I wondered if you would be willing to give me any pointers on how to make Thank you again!
I’m not very technical, but I building my site by myself.
I have tried other pugins like: RnB – WooCommerce Rental & Booking System. But I did not work like i wanted, it was not well thought out. I think GRAVITY FORMS is a trusted party, And all they offer works well.
Can you do something for me? Thank you in advance
Hi Edgar, GP Date Time Calculator is available by request for Gravity Perks license-holders.
I’ll send you the crash course video and can answer any additional questions via support. :)
okay so ive added the code to my functions.php file and i have two date fields, followed by a hidden field. How do i get the value into the hidden field? Am i missing a step? Do i need to set anything in the hidden field / date fields in the form settings? Does the gravity wizz plugin need to be installed for this to work as i haven’t purchased this?
Thanks
This snippet works on it’s own. The ID of your Hidden field should be passed as the “count_field_id” parameter. If you’d prefer to do this without code, pick up a copy of Gravity Perks and send us a request GP Date Time Calculator. It provides this functionality (and much more), just point and click.
GP Date Time Calculator looks useful! How would I go about trying it out? Not seeing it in Perks.
Hi Marty, it is available by request to Gravity Perks license holders. :)
Hi David, i want to use this snippet to calculate day from the user registration date. So i want to populate the first date field with user registration date. I try to use user_registered, but also if i see the correct date, this format doesn’t work with your snippet. Can help me? I want to limit the form only for users that are registered for more than a number of days :) Thanks Giacomo
Hi Giacomo, you’ll want to use the gform_field_value filter to create a custom dynamic population parameter (more information).
Your function will need to fetch the current user:
$user = wp_get_current_user();
And get the registered date:
$reg_dat = $user->get( 'user_registered' );
And then convert that date to a compatible format:
$reg_dat = date( 'm/d/Y', strtotime( $reg_date ) );
Ok, Works :) But in the code, the last row, you had insert “dat” instead “date”. The correct code is
$reg_dat = date( ‘m/d/Y’, strtotime( $reg_dat ) ); So the code works for me. It’s correct?
Yup, just a typo. :)
David,
Thank you for posting this code! It was a great help to me.
I wondered if you would be willing to give me any pointers on how to make this script work with any form without setting the form and field values when calling GWDayCount(). I am duplicating the same form on several pages, and cannot set the id’s each time a new form/page is created.
Each starting, ending, and counting field in my forms have a unique class associated with it. I was trying to use that custom class to find the id’s dynamically.
Thank you again!
Hi Brad, you might be interested in giving GP Date Time Calculator a try. It is merge tag based and since field IDs won’t change when duplicating a form, the configured field (for counting days) would just work on duplicated forms. If you’d like to take it for a spin, just pick up a copy of Gravity Perks and drop us a line via support.
Hello my friend, thank you for useful code, I have a problem, I want my user give his/her passport expire date and then the form calculate if it has 6 months valid time or no. I put start date : the expire date which user select via date picker and the end date : another date picker which in advance tab I set Default Value to {date_dmy} and other field for calculation result, but when I calculate it for example today : 10/06/2016 and the expire date: 11/06/2016 the result is : 118 ! for 12/06/2016 the result is 117. I didn’t give the URL because of it is not in English it is Persian but if you want to take a look I will update you with URL. Do you have any idea what is going on? Best wishes Bob
Sure, a URL would be great.
I have a hidden field that is getting the count just as it should. But I’m trying to use conditional logic to show another field based on the number of days. So for example show this field if days is more than 2. That’s not working. I can see the days hidden field gets set to the correct number which is more than 2 but the field with conditional logic never shows up.
Thanks for your help.
Hi Daniel, could you send me an export of your form and a copy of your configuration of the snippet?
Great! Thank’s a lot!
Now I want to calculate number of hours between two dates (or just calculate day as 24 hours). How can I add the calculated number of hours between start timestamp (merge date field and time field) and end timestamp (merge date field and time field). Please advice.
This is not possible with this snippet; however, it is possible with our GP Date Time Calculator plugin (available by request to Gravity Perks users).
Thanks David, I figure it out while experimenting on the gravity form. Thanks a lot.:)
Hi, I’m new in using gravity form and I finally make this two entry of dates work. Now I want the total value of this date to be multiplied to a custom number calculation field and tally the total to the pricing field before submitting to be check out for the shopping cart.
How can I add the calculated number field to the pricing field total value before submitting the check out button? Is there any back end customization for this logic. Please advice.
Hi Frances, you can create a Calculated Product field. It will allow you to set the product price based on a formula. Use the whichever field is populated with the number of days in this formula.
Hi, I’m wondering if something is possible… I have the GP Date Time Calculator Version 1.0.beta2.0, and GP Limit Dates Version 1.0.beta1.9. This is what I’d like to do…
If someone fills out a Gravity Form before noon, then they can select the next day, or the day after in the date picker. But, if it is after 12 noon, it is equivalent to the next business day and they can only choose + two days or + three days from today’s date. Is that possible?
Thanks.
Hi A Ghatit, you would need two separate Date fields. One with the ability to select next day and one that is the + 2 days from current date. You can then use conditional logic to show/hide these fields based on the time. Since the Time is not available in conditional logic yet, you can use GP Date Time Calculator to get the selected time in numeric format like so (screenshot). You would base the conditional logic on the value of this field.
Thank you for the response. That makes perfect sense, and I can work with that. One question… In your example you have this calculation: {Time:10} – {today}. Do you created a Time field on the form (field 10), but how did you set it so that it defaults to the current time? I don’t see anything obvious. Do I need to add something to functions.php?
Thanks.
Sorry – one other question… For the calculation, I need to exclude weekends (just count business days). I know how I can limit to just weekdays using GP Limit Dates, but the calculation itself will still include the weekends. So, if I’m saying you can go +1 for the minimum date and +3 for the maximum, and today is Friday, since the weekend is excluded, the customer should be able to choose Mon, Tue, & Wed.
Is there a way to do that?
Thanks.
The {today} merge tag is a special merge tag available with GP Date Time Calculator for use in calculations. It is replaced by the current date at 00:00. If you subtract the entered time from the {today} value, it will give you the entered time in hours (based on today).
There is another special merge tag available with GP Date Time Calculator that allows you to calculate weekdays or weekends.
{weekdays:{StartDate},{EndDate}}
A real example from one of my forms:
{weekdays:{Check-in:15},{Check-in:16}}
Thank you, again. You mention subtracting the entered time. Instead of calculating from a user-entered time, I want to somehow calculate the current time, without the user having to enter the current time. Is there something similar to {today} that will give me the current time?
My use case is basically I want to have a user-entered date field, and if the person brings up the form before noon, they can select +1 or +2 days (excluding weekends). If they bring up the form after 12 noon, they can select +2 or +3 days (excluding weekends). I understand from the previous response that I will have two date fields that I will conditionally show based on the calculated number field, but for the calculated number field, I need to somehow get the current time and subtract it from {today} to determine if it is before 12 noon or after.
The {weekdays:..} calculation would help if I needed to count the number of days between two dates, but I really just want to restrict the +1 and +2 parameters in the GP Limit Dates plugin to just count weekdays.
Thanks.
Sorry, A Ghatit, I may have wasted your time here. I tried to see if there was a way to accomplish this but the functionality just isn’t there. If this is something you’d like to commission, I’d love to talk more about it. Get in touch.
we need to exclude weekends form in calculate two date but this is include saturday and sunday plz help me
Hi Ramesh, pick up a copy of Gravity Perks and hit me up via the support form for a copy of GP Date Time Calculations which supports getting weekdays (or weekends) only.
Hello Devid,
Thanks for this helpful article!
I have a question: I would like to limite the date range of the first picked to “today” and second from first not more than 100 days?
Thanks!
Bought the Perks.
Is it possible to do Discount on a certain amount of Days? Also, is it possible to do max days?
You can apply discount pricing based on any number of conditions (including the number of days) via GP Conditional Pricing. In regards to max days, do you mean not letting the user selected a day more than X days in the future? If so, GP Limit Dates can help.
Questions.
How to I get the price field to show up? How do I hide the ‘Number of Days’ friend with css?
Not sure what you mean about the price field; however, you can hide the number of days field by adding the “gf_invisible” class to the CSS Class Name setting in the field settings for that field.
Great snippet, was wondering if there might be a way to vary this a bit….
I have a case where I would like to add 30 days to the date of submission (timestamp) and then use that as a merge tag in an email.
Basically, we want to issue a coupon in the notification email, that would have an expiration date of 30 days from form submission.
Thanks for any insight!
Hi Missy, this snippet is a better fit for that need: https://gravitywiz.com/populate-dates-gravity-form-fields/
Hi – 2 questions.
I have a license for Gravity perks. Can I get the GP Date Time Calculator plugin? Also, is there a way to exclude weekends from the calculation?
Thanks.
Hey there, yes and yes. Drop us a line via the support form and we’ll be happy to get you a copy of the plugin.
Love the plugin Here is where we used it http://saigonbbqs.com/rent-hire-bbq-grill-saigon-hcmc-vietnam/
2 questions – the field that results in the number of days. When I tried to make it hidden in Gravity Form settings, the calculations stopped working. Now I hid it via CSS and it works. Was there something special I had to do to use it as a hidden field
Hi Serge, if you made it hidden by setting the Visibility to “Admin-only”, the field was not output to on the frontend at all and this is why it would not work.
You can apply this snippet to as many forms as you need. Here’s more info on that: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Hi David, thank you for the great solution! It works fine, I have even expanded it a bit – needed to create something like booking form with highseason fee, so I used your solution and added two more days there – high season start and high season end… but I’m not very good programmer, so I still have question :) How do you think, is there a possibility to add backwards compatibility for these fields ? What I mean – user selects start date and end date. after that, he can see number field with quantity. So here is the question – can we change end date if user manualy changes quantyty field?
It is possible but would require some additional code. Something like this might help: https://gravitywiz.com/populate-dates-gravity-form-fields/
Hi,
How can i make it work on pricing fields? the total field?
There are two methods:
I tried the number solution but it didn’t work. for some reason the date fields are not in the formula insert merge tag. and in the quantity field the enable calculation is not there. what I’m doing wrong?
Hi Shahaf, you do not need to enable calculations on the Quantity field for solution #1. Just set the field ID of the Quantity field as the “count_field_id” parameter in the above snippet and the snippet will handle doing the day count calculation and populate that number into the Quantity field.
Hey David,
Just wondering: what if I would like this functionality not in multiple forms, but in one form on multiple different fields? Tried to make it work, but didn’t work…
Regards,
Johan
Hi Johan, see if this helps: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Hey David,
Same problem as Raymond here, but unfortunately I can not remove the {date_dmy} as I use that to auto-populate a hidden field to use as start field. Do you have any idea how to solve it?
Thanks in advance,
Regards from Amsterdam,
Johan
Ps: found the solution: the snippet does not work with the non-American date format (dd/mm/yyyy). Although I thought you updated for that, so I am not sure if I am doing something wrong ;-) ?
Regards,
Johan
Hi Johan, this should be working with non-US dates. See the demo here: https://demos.gravitywiz.com/calculate-number-of-days-between-two-dates-non-us-date-format/
Hello David,
The code works but showing jQuery error “Uncaught ReferenceError: jQuery is not defined” and makes my form very slow. Any solution for this issue? Error points to last line of script.
Hi Iliyas, the demo appears to be working fine with this snippet and the latest version of Gravity Forms: https://demos.gravitywiz.com/calculate-number-of-days-between-two-dates/ Do you see your error when the form loads or at another point? No suggestions on form slowness. I haven’t had been able to recreate any noticeable slowness on my end.
I see the error when I press next button. BTW I am using multipage form for Gravity form.
It sounds like this snippet does not support AJAX-enabled forms. Disabling AJAX should prevent this issue.
Yes, you are right. It was ajax but I want the AJAX to be true. So, can you please provide any solution?
I have a perk in development that supports this for AJAX-enabled forms (and much, much more). If you’re interested in the GP Date Time Calculator perk, pick up a copy of Gravity Perks and drop me a line via support.
Hi,
Where can I find “GP Date Time Calculator perk”?
It’s still in “beta” (pending new features, it’s stable enough for production). Here’s a quick video (originally recorded for another user) which gives a crash course on usage.
http://www.screencast.com/t/ya7Dd5rm0SSf
Hello,
thanks for this helpful article!
I have a question: I would like to limite the date range of the first picked to “today”, so I added the following line of code to my custom js:
$(‘#myStartDate’).datepicker({ minDate:0});
It disables the past dates, but it prevents the date calculation from working. Any idea?
Thanks!
Hi Marcello, the correct way to set a new property on a GF datepicker is via the gform_datepicker_options_pre_init JS filter. Just add this block of code to an HTML field on your form and update the formId and fieldId to match your form.
http://pastie.org/private/0h6rhjmtm0iwpxvxkkcyg#3
Hello David,
thanks for answering my question in such a short time! I was going to post the solution myself, I saw somebody made you a similar question in a previous post and you suggested to take a look at https://gist.github.com/richardW8k/515454542d1111e8c12c.
I have another question though. Probably it’s not strictly related to your code but maybe you can help me shed some light on my problem: I have some bits of jQuery in the page to create a price breakdown (taking the number of days and multiplying it by some other fields to show a total price to the user while she fills the form). It works, but if you try to submit the form and the page reloads with some error (for example missing mandatory fields), then my jQuery stops working. Any idea what it might be due to?
Hi Marcello, are you seeing an error? Also, is your form AJAX-enabled?
Hmmmmmm…. I can’t seem to make this work. I’ve got 2 date fields a result field (single line text – is this ok?)
I’ve put the snippet into functions (i’ve done this with some other snippets of yours fine.)
But the result field just defaults to 0. So something IS happening and populating the result field but not as expected.
Odd!
See: http://goo.gl/z2c2bu
Aha! I found the problem. This happens when I have set a default value in the date fields like: {date_dmy}
Now that I’ve removed these default values it works nicely ;-)
Small bug….
Interesting. Glad you were able to find a simple resolution. :)
Hello David,
I tried to apply the functionality to calculate the days between 2 dates (https://gravitywiz.com/calculate-number-of-days-between-two-dates/)! Nearly everything seems to work fine, BUT looking at the PDF date (&data=1) the calculated days a multiplied 2 times, so the sum of the price at the end is nor correct. The first calculation is correct. 80€ is the price per day. 7 is the number of resulting days (for example) =560€ (this is still correct
But then the 560€ are multiplied again with 7 (=3.920,00€)
and at the end the 80€ (price per day) are added to 3920€ =4000€ (the real total sum should be 560€ (=7×80€)
Screenshot with Pdf data and my commentaries in red: http://awesomescreenshot.com/04e4y3xn67
Could you please have a look whats wrong. I dont know anymore what to do!
Cheers, Gerrit
What is the PDF data? This snippet does not interact with the total. If you’re using it in a calculation, it should still work just fine.
Hi,
Excellent snippet, I’m wanting to know if it is possible to block out particular dates.
For example: I have an event package available that has two nights at a hotel included in the price, however, I’d like to set up a conditional logic question that asks if they want to stay additional nights. If they select “yes”, then I’d like to have the date picker show, but block out the days they are already staying, so their only option is to arrive before the pre-chosen date, or stay later.
Hi Ben, I don’t have a straight-forward solution for this but I wanted to point you to this resource which demonstrates of variety of ways to modify the dates available on the datepicker. You might be able to figure out a way based on this.
https://gist.github.com/richardW8k/515454542d1111e8c12c
Hi David, Great tutorial… i have one question we can use gravity forms add on for woocommerce, if user define return date while purchasing product and on that date gravity form field (datepicker) value add stock in woocommerce product inventory like any rental website?
Best Regards
Hi Abdul, I’m not familiar with any solutions that work with both GF and WooCommerce for this. I believe WooCommerce has their own scheduling product that might do the trick?
Dear David,
Really love this snippet. Got it working with calculating days just perfectly. While I am filling out the form the calculated field updates just fine. But when I submit the form, it does not save. When I go to the entries, the calculated field is empty. It seems to be since the latest gravity form update. Any suggestions how to safe the field? I cannot send it to another form either..
Thanks! Robert
Hey Robert, I’ll continue working with you in Gravity Perks support on this.
Great snippet of code. Thank you.
By any chance can the dates enter stay within the fields? For example im building a rental booking website. It would be awesome if the first time a user enters a date to rent a product when they go to another product page form the same date would appear.
Hi Carlos, this is possible with a bit of Javascript to save the entered date to a cookie and a little PHP (or JS) to repopulate that cookie into the field. I don’t have any ready code for this.
I found a great little code to copy and prepopulate fields. In case someone else is looking for the same functionality.
It will auto populate any field that is marked as “Allow field to be populated dynamically” with it’s previous value from a cookie.
Add this to your functions.php add it before the calculate between dates code above
http://pastie.org/10123477
Awesome! Thanks for sharing, Carlos! I moved the code to a pastie for legibility. :)
Hi there David,
Love this snippet, I even got your beta Perk to work with. A life saver, thank you so much.
But I have a new challenge. I need to calculate a date back in time and then count the days between now and then. To be precise: field_1 = a date in the future (user can set this date themselves) calculated_field_1 = field_1 – 280 days calculated_field_2 = days between calculated_field_1 and today The result in calculated_field_2 is a pregnancy duration in days (field_1 is estimated due date).
So tried to use something like this: {due date:2:age} – 280 for calculated_field_1, but this does not work. It seems that :age goes to -1 minimum.
Help would be much, much appreciated.
Thanks! Robert the Netherlands
Hi Robert, this should be possible with the GP Date Time Calculator. Can you ping us via the support form with these same details? We can help you work through the logic.
hi guys, any chance to exclude saturdays and sundays in the end result? thanks!
This is possible with the the GP Date Time Calculator perk. Available by requests via the support form.
Hey David,
First of all my compliments for the snippet; very useful!
Unfortunately, when I copied it in my functions.php, I got a warning that my plugin was deactivated, as I had created a fatal error:
Parse error: syntax error, unexpected ‘<‘ in /home/mhid1163/public_html/ghanaticketservice.com/wp2/wp-content/plugins/gravityforms/gravityforms.php on line 3156
Any way to solve this?
Thanks in advance!
Best regards,
Johan
Hi Johan, this might help: https://gravitywiz.com/documentation/snippet-troubleshooting/
Dear David,
My apologies; I did not follow the extra instructions down below the response form, and just had to remove the <?php.
Thanks a lot; it works great!
Best regards,
Johan Verhagen
Hey David,
First of all: thanks for your amazingly quick reply; highly appreciated!
Last question (hopefully); I got the snippet working, for as far as it calculates the days indeed. But somehow, linking it to the product prize and the ‘total’, does not work.
Is this because I do not have the Gravity Perk license and is it in ‘read only’ mode now, or am I doing something wrong?
Thank you,
Johan
Hi Johan, you’d need to use the merge tag for this field in the formula of a Calculated Product field. When the number of days is updated, the formula will be recalculated and the total will be affected accordingly. :)
Hey David,
Of course… Haha! It worked, thanks a lot =) .
Just wondering how you hide this calculated product on your site? It does work, but it works a bit as a double ‘total’ now: both the calculated product as the ‘total’ are showing the same.
If you’re using the latest version of Gravity Forms, you can hide it by adding the “gf_invisible” class to your calculated product field.
Hi David,
Is there any way I can limit the user to selecting dates that span a max period of 90 days for example?
Hi Eleni, you can do so by
1 – Adding a new HTML field to your form. 2 – Copy and paste this code into the content setting of this HTML field: http://pastie.org/9714044
You’ll want to update the “+2 W” to “+90 d” (2 weeks vs 90 days).
David,
Is there a way to get age of the user into the Age field, when user fills in his/her date of birth.??
Hi Jay, this is possible with the upcoming GP Date Time Calculator plugin (available now by request to Gravity Perks license holders). You just install the plugin, add a Number field, enable calculations, specify your Date field merge tag and at the “:age” modifier.
{Date:12:age}
David,
Thanks! I have managed to use jQuery for now to get the age from the dob date picker and made it readonly so that the user cannot edit the age.
This snippet was working great until I updated to the latest version of Gravity Forms yesterday. Has something changed? Thanks!
Hi Brian, try getting the even-more-latest version of Gravity Forms from the downloads page and also re-copy-and-pasting this snippet over the previous version. There have been updates to both since yesterday.
Hi David, I updated to that version, updated the code to the above and it’s still not calculating. Any ideas? As always, thanks for your help!
I’d try testing for a theme/plugin conflict next. I just made sure the demo was running the latest version of GF and latest version of this snippet and it is working.
Thanks David. I gave that a try and it still didn’t work. I’m sure it’s something on my end. I ended up reverting to the previous version of Gravity Forms and it is working again. I’ll give it another go around on the next update. Thank you!
Hi, Nice work. I have just one issue with the sniet, why does it give weird calculation results if you have the dates in non US format?
Thanks
Hi James, I’ve just made an update to the snippet to fix this. Give it a try and check out the non-US date formats demo.
Hi, How to implement the snippet on multiple forms — especially on the same page? Could you please guide as I’m no expert in php. Thanks.
You just copy this part multiple times like so. Note that the form ID and other parameters have changed to accommodate the second form.
http://pastie.org/private/ztudvgssl0zi4p3wdpseq
Hi David, This is maybe a stupid question, but I had to ask one thing — as I’m not expert in php — about the new ‘instance’ you’ve stated above.
So, if I need to have it on another form, do I need to copy-paste the whole code with a new parameter or just create a new set of parameter?
new GWDayCount( array( 'form_id' => 1, 'start_field_id' => 1, 'end_field_id' => 2, 'count_field_id' => 3, 'include_end_date' => false ) );
and then create another below it with this?new GWDayCount( array( 'form_id' => 2, 'start_field_id' => 1, 'end_field_id' => 2, 'count_field_id' => 3, 'include_end_date' => false ) );
Would you please help? Thank you in advance. Regards, prSetiadi
You’ve got it right. Just create a new copy of the new GWDayCount( array( … ) ) bit like you’ve demonstrated. :)
The code is good, but how about if I want to exclude weekends in the count? Thanks
Hi Arven, to exclude weekends you’ll want to pickup a copy of Gravity Perks for access to the GP Date Time Calculator perk. This plugin is really powerful. It uses the GF Calculation field so you don’t have to touch any code. It offers a special merge tag for calculating both weekdays and weekends. Here is the weekday merge tag:
Simplified
{weekdays:{startDate},{endDate}}
Actual Example
{weekdays:{Check-in:5},{Check-out:6}}
The GP Date Time Calculator perk has not been officially released yet but it is available by request for Gravity Perks license holders.
Hello David,
I need a good solution for a rental-service, which offers different products for rent. Is it possible with the help of “GP Date Time Calculator perk” to calculate different prices for weekdays and weekends?
Example: Weekend-special: Renting from Friday to Monday results in discounted price Regular: Renting between Monday and Thursday -> fixed price per day
It sure is! To calculate the number of weekend days between two dates, you would just add Calculation field to your form and use the following merge tags:
{weekendDays:{Start Date:1},{End Date:2}}
. So basically{weekendDays:DATERANGE}
. You would then take the number of days and multiply it by your different rates.Here’s an example based on reserving a room at a hotel:
( ( {weekdays:{Check-in:5},{Check-out:6}} ) * 150 ) + ( ( {weekendDays:{Check-in:5},{Check-out:6}} ) * 250 )
We first get the number of week days and multiply that by $150 (our weekday rate) and then we get the number of weekend days in the same date range and multiply that by $250 (our weekend rate).
Hey David,
I bought Gravity Perks and tried to put GP Date Time Calculator perk into use. I tried using your example-snippet to start out, but it doesn’t seem to work right. It doesn’t matter what date-range is picked, the price always goes to 150.
See here: http://tischemieten.de/test/
Thanks in advance
Hey Adam, just responded to your support ticket.
Hi,
Great Addon, but may I know how can I add the day(s) word on the date after, like below :
E.G. 12 days <– output result
Thanks a lot (=
Hi Carrie, your comment was lost. I’m sorry about that. I don’t currently have a solution for this.
I have identical issue as
“I have setup the date inputs with format dd/mm/yyyy. This causes the following problem: when I set a starting date at Oct. 1 2014 (the preview date for some reason it converts to 10/01/2014 instead of 01/10/2014 ) and end date Oct. 2 2014 (same here preview date converts to 10/02/2014 instead of 02/10/2014) the count result is 32 (it counts the days from Jan 10 2014 to Feb 10 2014).”
Do you have a URL where I can view this?
yes, thanks.
http://www.positivelendingsolutions.com.au/round-robin/
I still have not been able to locate the issue with non-us date format.
Any suggestions are welcomed
Hi Adam, I sent you an email requesting a form export. Looking forward to getting this sorted. :)
Thanks,
I had replied but perhaps spam filter caught it. Although I sent a full export of the form that time.
I just sent an export of a basic form with 2 dates and the count field where the issue is replicated.
Hey Adam, I’ve just made an update to the snippet to fix this. Give it a try and check out the non-US date formats demo. I tested with the demo form you sent over and it is working for me with this updated version.
Thanks for your help David, the snippet update worked a charm to fix the non-us dates!
Glad to help. Thanks for staying one me. ;)
Hi I can’t install the snippet Help
Thanks
Try this: gravitywiz.com/documentation/snippet-troubleshooting/
Hi David,
The company I work for is looking to calculate the amount of time between two time fields. I saw you mentioned above that you have a snippit in the works that might solve this issue and that it’s currently in beta. Any progress on that? We’d be happy to test it and to pay for a solution.
Thanks! Ryan
Hi Ryan, yes, the upcoming GP Date Time Calculator can handle this. The beta is available for Gravity Perks license holders. :)
Hello I commented last week about getting this code to work using a UK time format, the same issue as Stelios on October 18, 2014 at 1:05 pm.
I am guessing that these comments are moderated before they come up on the site. I was wondering if you had seen it.
If for some reason it didn’t go through. The issue was to get the code snippet working with a UK format. Is there a solution. if you would like to email me directly then please feel free, or if you would like to me email to you directly then what is the email address to use?
Thank you
Reece Cropley
Hello, Thanks for some great code.
I am experiencing the same issue as a few other comments. Its the date format. I am using this for a UK based website and I will need to the date format in DD/MM/YYYY.
When the form date fields are set to the UK format the calculations do not work. Was there a version of this code that included the other date format?
Thanks in advance
Reece
Hi David,
I have the same situation as previous comment;
Awesome add-on!
Can we get this to work on multiple areas of one form; eg: moved in date, today’s date = days at current address moved in date, moved out date = days at previous address
Thanks in advance
Also I have same issue with date formats dd/mm/yyyy
I tried to purchase the Perks and each time I enter payment info, I get a page that says my cart is empty. I am trying to buy the Perks so I can use this snippet. Please help.
Thanks for sharing this fantastic snippet, it’s incredibly useful.
I was wondering if there was a simple way of excluding Saturday and Sunday from the total number of days? I need to total the amount of working days (mon-fri) in a date range.
Many thanks :)
Dear David,
Great snippet! Thanks a lot. Love to use it with the read-only Gravity Perk field. But do you think I can also use it to calculate years? It would be great to have a user set their birthday, and then have a field with the age in years.
Thanks for your help! Kind regards, Robert the Netherlands
Hi Robert, responded to your email. This is possible with the upcoming GP Date Time Calculator perk. It’s still in beta but is available by request for any Gravity Perks users.
Hi and thanks for the code. I have the same problem as Marieke. I have setup the date inputs with format dd/mm/yyyy. This causes the following problem: when I set a starting date at Oct. 1 2014 (the preview date for some reason it converts to 10/01/2014 instead of 01/10/2014 ) and end date Oct. 2 2014 (same here preview date converts to 10/02/2014 instead of 02/10/2014) the count result is 32 (it counts the days from Jan 10 2014 to Feb 10 2014). You can see an example here: http://www.misthodosia.eu/test/ I am using Gravity Forms 1.8.17 Is there a way to fix the format problem? Thanks!
Just sent you an email requesting more information.
Hi,
First of all, love this code, we have been using for a while now on a clients website, but after the Wrdpress update it’s working properly. I have changed the code into the above version, but it gets the dates wrong, the start_field_id and end_field_id have changed into a different format. In Europe we use d/m/y but as soon as I change the code, the format becomes m/d/y, I have looked over both the old and the new code, but I can’t seem to figure out why it is changing, the code looks almost the same.
Do I have to change the date-format in the code to d/m/y?
Do you have a URL where I could preview your form with this issue in place?
Awesome! Anyway to get a count of weekday days AND weekend days? Thanks!
Hi Will, this will calculate them together. Do you mean you want to separate counts for weekdays and weekends between two dates?
Thanks for the quick reply! Yeah, I’m curious how to separate counts for weekdays and weekends. I think just about every reservation for hotel or B and B that I’ve worked on always has different pricing structures for weekdays and weekends. Some even include Friday in their weekend pricing.
Thanks!
I have a perk coming soon that will allow you to do this. It’s called GP Date Time Calculator and it will take the functionality covered in this snippet and give it a heavy dose of cocaine. It will also allow you to calculate the number of weekdays and/or weekend days between two dates.
If you’re interested, pick up a copy of Gravity Perks and drop me a line on support to get early access to this new perk.
The snippet is not working with the last version of Gravity forms.
I put 2 days, and he gives me a total of 30 days. I put 3 days and the total is 202 days :S
Can you see that?
http://www.jphgo.pt/inscricoes/#gf_3
Hi Fernando, what version of Gravity Forms are you using?
David,
I know we just communicated regarding some of the address and geo-mapping scripts. I’m working with a developer to design either modifications we discussed or another plugin. Hopefully will be done in a couple of weeks.
But I have another need, and was hoping you might be able to guide me. I need a “Time Calculation” – Basically, when a user selects a time on our forms, I need a field to subtract about 90 minutes, plus a time (usually in minutes) that will be sent back from our Mapping script, and copy the new value into another “Time Field”.
To make this more clear, a customer or our dispatcher will select a time for Airline Flight Departure. From that time, we will subtract 90 minutes (Airlines recommended time for arrival before flight departure), and subtract another specified amount of time for travel on the distance (based on the time to travel route returned by the Geo/Google Maps Script we are working with), i.e.: 20 minutes. This will then put on the form the “Recommended” pick-up time for the reservation.
It seems that some of the basic code is already there from the “Calculate Dates” script/perk we are using. What I’m trying to figure out, is how to modify or add those calculation functions into a hidden calculated field for time.
Thanks for any guidance. Or if I need to, I’ll see if my coder can add this to my other stuff.
Thanks,
Ron
Hi Ron,
Can you drop me a line via the Support Form. I’ve got a new perk in the works that should be able to handle this with ease. I’d love to get the early beta in your hands for some testing. :)
Hi, thanks for sharing. I’m trying to make this work, but the number of days shows first after a page refresh. Is there anything I have to set in the “receiving” form field?
http://www.oransje.com/utvikling/wc_dev/?page_id=214
Hi Tom, I’m not sure I understand your issue. I took a look at the form but it doesn’t appear that the snippet has been configured for this form yet?
Yes I configured it like this. And at least something is happening since the number of days shows after refreshing the page…
new GWDayCount( array( ‘form_id’ => 9, ‘start_field_id’ => 9, ‘end_field_id’ => 10, ‘count_field_id’ => 13 ) );
Hi Tom, I was able to recreate this issue. I’ve updated the snippet. Get the latest code above.
Brilliant, thanks a lot for your help!
Happy to help. :)
Hey David,
Thank you for sharing the script, it was a life saver. Perhaps you can save me one more time :-). I am trying to take to fields with Postcode and Address, and find the distance between them, depending on this distance a delivery fee is calculated. I tried to emulate using the example of the dates, but had no luck. Any guidance you can offer? Once again thank you for sharing this script and glad to have found your website.
Have a lovely weekend.
Cheers Ratna
Hi, Ratna. Your question is a little open ended. You’ll probably be better off hiring a developer to assist you with this one.
Ratna,
I may have your solution. I paid for a developer to program a script, which takes two address fields data from Gravity Form #1, sends it to Google Maps, and calculates the mileage, then passes that data back to Gravity Form #2 in Step two, including mileage, and addresses to complete a customer reservation for local airport shuttle company. We base the rate on the mileage returned, and also use the Map data to pass on to the drivers.
If you are interested, I would be willing to share what I have for a fraction of original investment I paid the developer.
Contact me via email ron@sfiremedia.com
Hi David, We are using your code snippet and it is very useful to us. Based on this script, we are trying to calculate the distance between two post codes,Based on the distance, we have to display the price on the third input field. The price need to be added to the total automatically. We are using google maps to find the distance between the post codes. Can you please suggest how can we do it. Any help is appreciated.
Hi Sunil, check out Ron’s response here. Sounds like he might have a solution for you.
https://gravitywiz.com/calculate-number-of-days-between-two-dates/comment-page-3/#comment-177981
Hi, I have a form for a sort og booking quotation. The form uses two step (I’m still developing it) and in the 2nd step, when I choose the second date (“Data di partenza da Friburgo”) I get the error TypeError: format is undefined format = format.split(‘_’); Line 233
Could you help me? The plugin works also in multple-steps form?
thank you, Denis
Hey Denis, sent you email requesting more details.
Sorry David, at the moment the error is disappeared! My mistake I think.
Awesome! Let me know if it pops up again.
Your instructions are grey. Even a newbie like myself has been able to make this work. My question is, is this possible in Gravity Forms?
Calendar function: Entry date ==> selected by customer ==> April 15, 2015 Number of days (nights) ==> selected by customer in drop down field ==> let’s say 3 Automatically show the exit date of ==>April 18, 2015
Hi Jane, this isn’t currently possible (without additional custom code) but I’m working on an awesome new perk that will handle this beautifully. I’ll notify you as soon as it’s ready. :)
I am also looking at let’s say holiday season pricing calculations and am wondering if this is even remotely possible.
If the start date =< than December 13, 2014, and end date is = >January 5, 2015 add 10% to a hidden field that can be used later in the calculations.
Normal Daily Rate = $500.00 Inquiry is for December 15 to December 19 (nights = 4) $500 x 4 X 1.1=$2,200
Just wondering if this is possible.
Hi Letty, there are two ways you could accomplish this. Once requires custom code the other is available in plugin form.
Custom Code: https://gravitywiz.com/use-gravity-forms-conditional-logic-with-dates/ Plugin: https://gravitywiz.com/gp-conditional-logic-dates-first-draft/ (it’s much farther along now than this post indicates)
Hi David,
I couldn’t find a “Contact” form to submit this request through but is it possible to modify this snippet to calculate numbers between gravity forms “Time” fields; like an employee timeclock?
This snippet won’t do that for you out of the box but if you’re interested in commissioning the customization, I’d love to add support for it. Get in touch!
Hi David, Thanks for the code snippet, its very usefull! I was wondering, what do i need to instead of showing the number of days, use the numer of days in a different place of my script. Im not that familiar with JS/Jquery and i cant seem to wrap my head around it.
Egbert
Hi David– Great snippet. I’m curious how feasible it would be to calculate the number of days between today and a date in the past in order to calculate a late fee. Essentially $1 a day past May 20. I think this snippet is pretty close to what we are looking for, but we would need to get this into a product calculation to add to the order total. Thanks for your insight.
I pasted the code at the bottom of my theme functions.php and included the following lines below the code but it isn’t working and am not sure what the problem might be:
new GWDayCount( array( ‘form_id’ => 1, ‘start_field_id’ => 6, ‘end_field_id’ => 7, ‘count_field_id’ => 26, ‘include_end_date’ => false ) );
Please help me asap.
Hi preeti, I’ve written up some troubleshooting steps. Let me know what you determine.
Thanks !
I pasted the code at the bottom of my theme functions.php and included the following lines below the code but it isn’t working and am not sure what the problem might be:
new GWDayCount(array(1,6,7,26,false));
new GWDayCount(array(1,21,22,27,true));
Please help. The first is to calculate number of nights for accommodation while the second is to calculate number of days for car rental. ‘
URL is http://makeitnigeria.com/submit-booking/
Hi Dayo, you need to include the “keys” for each of the values in the parameters passed to the GWDayCount class. Currently, you just have the values. If you look at the usage example, you’ll see that the keys should be preserved (i.e. ‘form_id’, ‘start_field_id’, etc).
Hi David, maybe its unrelated but maybe you can help. I found age verification snippet for gravity forms, but it won’t work with date field because $dob = rgpost(‘input_5’); not return string value. How to make it work for date field?
Here is the source: https://clicknathan.com/web-design/gravity-forms-age-verificatio/
If you can help, maybe answer through comment or email me directly. Any help greatly appreciated
Hi, Am i correct in concluding that this does not work if you set the visiblity of one of the fields to Admin Only? I want to enable some fields based the results, but I dont want the user to see the enddate and resultfield. How can i accomplish that?
gr Bas
Hi Bas, you are correct. Admin Only fields do not actually get output to the page and are pretty much ignored by Gravity Forms until submission. You’ll want to hide the field via CSS by setting the “CSS Class” setting to “gf_hidden”. It’s a built in class for hiding Gravity Form fields.
David,
Your date calculation has been amazing!!! With some recent updates though, a conditional logic html field that was “hidden” before based on the “default value” of my ‘count_field_id’ (Days in Advance) is no longer pre-populating that field with my outrageous number. To explain more: I have the count_field_id, advanced field, “default value” set to ‘99999’. Then in the html field I want to show/hide, I have conditional logic enabled for “all” – 1)Show if Days in Advance – Is Less Than – ‘2’ & 2) Show if Days in Advance – Is Not – ‘99999’. The “Days in Advance” field is hidden with gf_hidden. But I’ve checked and when the form loads it’s not pre-populating with the ‘99999’. I’m not sure where it’s bogging down, but think it may be in the GWDayCount script. Any ideas?
BTW: Form is here: https://shuttleexpressutah.com/reservations/airport/
Hey Ron, could you send me a copy of your functions.php file and an export of your form? Alternately, if you’d like to just send me a WP login for this site, you know my gravitywiz.com email. :)
Hi, David,
I need calculate time in hous a minuts, into two times ( time start and time end) and the result publih in input in gravity,
what is the code?
Hi Sergi, you can update this line (199):
$day_count = $diff / ( 60 * 60 * 24 ); // secs * mins * hours
to:
$day_count = $diff / ( 60 * 60 ); // secs * mins
…to convert the day count to minute count.
I’m looking for a way to have my form allow for a dropdown number based upon what month of the year it is. In July, it would allow a choice between 1-10, and each following month would allow one less option: August, 1-9; September 1-8, October, 1-7), etc. Ideally, once the coding is set, it should work year after year. Do you think your snippet could help to accomplish this goal?
Hi Wendy, this particularly snippet probably won’t help much; however, the Use Gravity Forms Conditional Logic with Dates article will get you much closer. It’d would still be a bit of manual work as you would need to set the start and end range for each month for each condition and then you would need to update that at the beginning of each year with new timestamps for the month ranges.
I’d love to add support for this to my Conditional Logic Dates perk. It is a planned feature but I’d be happy to prioritize it if you’d like to commission the feature.
Great snippet – thanks. I needed to show years rather than days (to calculate a person’s age after they input their date of birth), so I aded this line:
dayCount = Math.floor( dayCount / 365.2425);
after this one:dayCount = Math.round( dayCount ) + this.options.countAdjust;
365.2425 is the real number of days in a year. This may be useful to others with the same scenario.
Thanks for sharing, Adrian!
Thank you for this post is indeed a life saver. However, i want to use this for an travel insurance product where price will be based on the duration of the time that will be spent for the trip and additional price for other individuals or family members based on their date of birth
Hi OLA, I’d need more information on what you’re trying to accomplish and where this current solution is falling short to better advise on alternative solutions.
Can I get same functionality for Java?? I think it is for php only.
Hi Prashant, this blog is for Gravity Forms, a WordPress plugin which runs on PHP. I’m not familiar with Java. Best of luck finding a Java version. :)
Hello David,
Thanks for you fast reply and the offer.
I read some things about php code and code it myself yesterday. If there isn’t an week selected the code will return -1. After that you can make a error code on that -1. After I found the sollution it was quite easy to implement.
The only thing thats left is the same problem as Sebas, different prices for different periods. For example the holidays are per week more expensieve than normal weeks.
Thanks again.
Hello David,
Nice Snippit! Works fine!
I use this snippet for pricing a rental home.
But some days are more expensieve than others. So is basically have the same question as Sabas?
Also i would like to add a functions that gives an error when the number of days are not correct. You can rent the place only for 7, 14, 21 etc days. Is there a way you can integrate this into this snippit?
Do you have a sollution for both problems?
Thanks in advance!
Hi Rens, I’d love to add support for counting only week days and only weekends. Are you interested in sponsoring this enhancement? I’d estimate about an hour of effort. My hourly rate is $100. Contact me here if you’re interested.
Hello David,
Thanks for you fast reply and the offer.
I read some things about php code and code it myself yesterday. If there isn’t an week selected the code will return -1. After that you can make a error code on that -1. After I found the sollution it was quite easy to implement.
The only thing thats left is the same problem as Sebas, different prices for different periods. For example the holidays are per week more expensieve than normal weeks.
Thanks again.
Hi there. I need your help.
Price calculation have some problem. below: product:Field ID 10.see how the form currently works. ( {Insurance:9} * {Number of Days:3} + {Battery Option (Extra Battery):8.2} * {Number of Days:3} + {Battery Option (Portable Charger):8.1} * {Number of Days:3} + {Select Single Country:7} * {Number of Days:3} ) –> it means (Mobil WiFi + Battery Option + Insurance) x Days Rental = Rental Price
this is work but Total Price Number(total in cart woocommerce) is wrong. Can I remove total price in cart? or some any tip?
please help. Thank you.
Does this work when not used in combination with WooCommerce? Do you have a URL where I could see this in action?
Hi Dan,
I use this snippet for pricing for a car rental website. But is there a way to price by day and weekends? ‘Cause if you rent a car in the weekends it is cheaper. And if you rent a car for 7 days it is cheaper also. Example: 1 day costs 29 euro, but 7 days will cost 174 euro. A weekend costs 49 euro.
Thanks in advance!
Hi Sebas, I’ve sent you email response.
Hi there.
I need your tip. Please see here http://xcom-dev.com/product/multiple-plan
It doesn’t work. “Total$ 0.00”
Looks like you were able to get this working?
Yes! And I did it. I like this gravity form! This is so nice. Thank you for your help! And I’ll try another one ;)
We have already purchased personal version of gravity form. However, we need to “Calculate Number of Days Between Two Dates” in form. So do we need to buy any pulgin from your site or just need to follow this article https://gravitywiz.com/calculate-number-of-days-between-two-dates/
Please advise.
Hi Vino, you do not need to purchase anything else. Just follow the instructions and you’ll be good to go. :)
Thanks David, now it’s working fine. Another one help i’m trying “Arrival date and return date”.
with the calendar it is possible to select a arrival date on 02/12/2013 for example and a return date on 01/02/2013 which is a problem because people may make a mistake.
Please advise.
How about doing this with time having either a start and stop time as a drop down and then a read-only field that calculates the time difference?
Hi Ken, it actually might work if the dates in the drop down’s option values are in the same format as the datepicker field would be. For read only functionality check out Gravity Perks GP Read Only perk.
Really want to apply this to return a date which is a specific number of days before a user selected date.
Hey David! Love Gravity Forms and this is an awesome addition! Is it possible to use this method to calculate the date that is “14 days from today”? For example – someone signs up for a free trial via your Gravity Form – and on the confirmation page and in the conformation email you want to show them the date on which they’ll be billed – which is “today + 14 days” Thanks!! :-)
Hey Dan, this is definitely a good idea. This snippet has the foundation for such a calculation but it would need to be customized a bit to actually work per your requirements. Keep bringing this up and I will tackle it one of these days.
Hi, What would I need to do in order to check if person is 18 or older? For a form I am building, I want a parent waiver to be required if not 18 years old.
Hello, thanks for your tutorial, But I have a problem , how to calculate between two dates basiccaly of 24 hours? for example if start date on 01 jan 13 and end date 02 jan the result is 1 not 2. Thanks for your attention
Hi Aira, sounds like you just need to set the
"include_end_date"
tofalse
when you initialize the GWDayCount class. Take a look at the Count “Nights” Only example above.Hi, Just wondering if it’s possible to adjust this code to provide the difference between two time fields? Thanks :)
Thank you very much for this plugin! There is only one issue.
I am using a form with conditional logic (a Gravity Forms’ form of course). Moreover I call in inside my template with gravity_form(..).
In HTML source code the form is placed inside a div with the following attributes
<
div class=’gf_browser_gecko gform_wrapper’ id=’gform_wrapper_4′ style=’display:none’>.
I already know that all conditional logic forms are styled with “display:none” which gets removed by your JS (if there is no error). But there is an error.
I wanted to be sure before posting this and went through my plugins many times, deactivated all and tested each separatly.
So, all in all it seems as your above plugin causes the JS error “Uncaught ReferenceError: jQuery is not defined”.
Without conditional logic in a form your plugin works like charm!
Best, Pete
I have to add that the JS error “Uncaught ReferenceError: jQuery is not defined” also occurs without the above plugin only with Gravity Forms (checked all other plugins and the theme I am using; deactivated all and tried TwentyEleven)+ multi-page-form + conditional logic + gravity_form(..) in template.
But I managed that with “gform_init_scripts_footer”. Activating your plugin again the error re-occurs. Chasing the problem I tested my thesis many times.
I want to tell you that I could solve the issue.
The problem was that I moved all GF scripts to the footer (by gform_init_scripts_footer).
So your plugin’s JS was still line before jQuery was loaded.
In your plugin I set
…
Now everything works properly. Sorry for inconvience but maybe others will face the problem as well.
Best, Pete
Oh my gosh, sorry again. The script and php tags were removed by comments section.
I put your plugin’s JS in a php function like this:
function script_to_footer { ‘opening tag JS’ [your JS] ‘closing tag JS’ ‘php’ add_action(‘wp_footer’,’script_to_footer’,100)’php’
I’m kinda new to this but I reckon this can also be integrated into woocommerce as well? I already got the extension for gravity forms for woocommerce but I’ve been looking for a way to sell my car rental service using the datepicker to calculate the booking by using both plugins (gravity forms + Woocommerce).
Any help would be awesome!
David, You sir are a gentleman & a scholar.
Question, How hard would it be to do prices based on amounts of days?
For example Minimum of 7 days = $50 per week. Each additional day is $8 until the second week etc.
Love this site and GF 1.7.5! but… I’m getting an Uncaught ReferenceError: jQuery is not defined. from line 127. Our site includes jQuery 1.8.3 in the . Ultimately trying to modify this snippet to calculate total hours from 24 time pickers. Also looking for an easy way to default to PM instead of AM for evening time pickers.
hi .. i am new to development..i need a help. i want to calculate the number of leaves taken by employee between two dates along with am and pm. suppose the dates is like 31-05-2013 am to 31-05-2013 pm the leave should show as 1 day .how can i consider am & pm while calculating the leave. kindly help
Hello-
this is what I am looking for but can’t get it to work (i’m sure I am missing something simple in my setup). nothing ever populates ‘the count_field_id’
what I need to do is calculate the date picked/entered in – against the current date + 3o days. if the dated picked is greater (more than 30 days out) then show the rest of the form.
basically its a date check to make sure they are picking a date at least 30 days in the future.
any help would is greatly appreciated.
thanks-
Hi David, you great, how to count per month?
Which version of GF does this works with?
I tryed with 1.6 without success :-(
Hi Zlaja, it was developed on 1.6.11. You can upgrade to the latest Gravity Forms for only $39. Gravity Forms 1.7 is amazing. :)
David, I’d like to kindly second the request for this to work with two ‘Date Drop Down’ fields.
Would love to know how to add a specified number of days to a date field. e.g. today +14 days… We would use this as follows: “You will not be billed until the end of your 14-day free trial, your credit card will be billed $12.00 on “x” date”
Would it be possible to add in support for the “Product” field type’s Quantity field? The ID differs from the parent field type’s ID.
I’ve managed to do it manually by changing the jQuery selector to “#ginput_quantity_” rather than “#input_”.
Bloody awesome snippet by the way! :D
Hiya – any possibility for it to support a working week calender – ie does not include weekends? in the calculation ..
David, I am “really” new to Gravity Forms. Your snippet looks like what I need. I have a form, that I pass “arrival date” from the previous web page. The user then enters the “Departure date”. I need to know the # of Nights they will be with us. 1. You state it only works with Date Picker fields. Will it work ok if I define my field as date picker, but auto populate it? 2.instantiated – I don’t quite understand this. Do I add GWDayCount() to the end of the Functions.php? 3. Where do I “Call” this function?
Thanks.. I am surprised that this is not a standard function in Gravity forms.
This is absolutely incredible! Thank you. One thing I do notice is that it breaks the form if you use any type of conditional logic. The form doesn’t show. Any ideas on why this happens?
Hi Brian, thanks for letting me know. I’ve updated the snippet to support forms with conditional logic.
Thank you David. The updated snippet did the trick! I’ve sent you a donation. You are much appreciated!!!
Hi David,
Thanks for the information,
I actually do not have a link, because I’m developing on localhost, but I’ll check my functions.php carefully and try it again.
This doesn’t seem to work with me;
I am using a multi-page form; is this the reason?
The form goes blank, when I add the code. As for the ‘count_field_id’ parameter, what type of field should this be? A single line field?
I am using a date picker field on both ‘start_field_id’ & ‘end_field_id’ parameters.
Also does the opening ‘<?php’ tag need to be there for this snippet to work? It’s causing a syntax error with other functions in my functions.php
I am using the latest Gravity Forms version also.
Thanks for the help in advance!
Hi Lewis,
The opening ‘<?php’ tag is simply to indicate that the code is PHP code. If you are pasting this in your theme’s functions.php file and an opening PHP tag is already present, you can safely ditch this from the beginning of the snippet.
The ‘count_field_id’ is not limited to a specific field type but is probably best used as a single line text, hidden or number field.
I just tested this snippet on a multi-page form and it worked without issue. Do you have a link to the form you are developing?
Hi there,
It would be great if this could work with the ‘Date Drop Down’ field also
Thanks
Thanks for the suggestion. If I get enough interest, I’ll be happy to add support for this date field type as well.
Hi David, your snippet has helped me to solve a big problem in an easy way. Much appreciated. However, I found out the “Date Picker” does not always work to supply an accurate price. Would you consider publishing a snippet with “Date Drop Down” anytime soon? Cheers.
i am very close. i want to build a car rental system! and transfer systemn the transfers is in the finish! i take the range of day, i create my price…. but the price is not change if the user change the months..
hi men….. your snip is the best!!!:) i want to ask if this snipet cant work with month if the price in january is 10 e on september is 15 e! he can calculate?
Hi Chris, it sounds like what you want to do is conditional logic based on the current month. Is that right? If so, this tutorial will get you started:
https://gravitywiz.com/use-gravity-forms-conditional-logic-with-dates/
1 – Use this snippet instead of the one provided in the tutorial: http://snippi.com/s/mtvseuc
2 – Instead of “Setting Up Time Stamp Field” you’ll be “Setting Up Current Month Field”, only difference is instead of using “timestamp” as the dynamic populate parameter, you’ll want to use “current_month”.
3 – When you get to “Setting Up Conditional Field”, you’ll just need to remember that you aren’t working with a time stamp, you are working with the month as a number (ie January = 1, February = 2, March = 3, etc). Here is an example of a product field that will only show up in the month of November: http://grab.by/kpQE
If anyone else is trying to do this and finds it useful, I’m happy to write up a full article.
Hey David,
This is an awesome snippet. I’m having a little bit of an issue when I load this into my functions.php file. It seems to break the form completely, this is probably something I am doing, but could you give me a hand with correctly implementing it?
Hi David, wow, awesome! Just what I need, however when I use this picking one night (two days) it calculates 32… I think it has to do with my dates being dd/mm/yyyy, not mm/dd/yyyy?? can you suggest a work around please, I would ideally like to keep the dates displaying dd/mm/yyyy…
Also when I tested the mm/dd/yyyy theory the “nights only” code option doesn’t seem to calculate correctly, eg if I pick 1st March for day one and 2nd March for day 2 it gives a calculated total of 2 (whereas I want the total to read 1). Thank you in advance for your help
Hi David, I’ve updated the snippet to better support the different date formats and fixed the issue where the “nights only” option was not working. Give it a go and let me know how it goes. :)
That works perfectly now, you are a star! Thank you!
Can I use two of these? That is, I want the user to put in a date. I want to calculate the number of days between that date and the date the form is opened. Then, I have conditional logic based on the size of that field. The question is, can I then repeat that process with subsequent sets of dates?
Hi Gary, couldn’t before, thanks your comment, now you can! Here is an example:
http://snippi.com/s/c6o9g1f