How to calculate the number of days and hours between 2 dates?

  • Profile Image
    LindaC88
    Asked on June 29, 2017 at 03:03 AM

    I use calculation field "Number of days" on my form. There is also an extra field "Hours".

    How can I set that number of days is calculated as 2 days if it is over 24 hours? Till now it calculates only by date.

    For example, 1st of Septembet 10.00 - 2nd of Septembet 12.00 should be calculated as 2 days, because it is over 24 hours.

  • Profile Image
    Jim_R
    Answered on June 29, 2017 at 05:13 AM

    You have to convert the difference between the date fields into Epoch time first (number of seconds) to get the remaining hours less than a day. If you need it to be broken down to just the number of days then number of hours, here's how you will do it.

    1. Add 3 Form Calculation Widgets

       - 1 for the Epoch difference

       - 1 for the Days

       - 1 for the Hours

    Related guide: How-to-Add-a-Widget-to-your-Form 

    2. Set the Epoch calculation as follows:

    (Date2-Date1)*86400

    We just get the epoch difference in seconds that will be used in the calculation

    3. Set the Days calculation as follows:

    floor(Epoch Difference0-9/86400)

    The floor() function rounds down the quotient so it's a whole number. This will represent the number of days.

    4. Set the Hours calculation as follows:

    ((Epoch Difference0-9/86400)

    -Days0-9)*24

    We had to subtract the floored quotient from the regular quotient to get the decimal place (or the remainder) of the division. Then we'll multiply it by 24 (the number of hours there are in a day) to get the remaining hours.

    Here's a quick demo form with 2 Date Picker Fields similar to your current setup. I emulated the settings of the Date Picker Fields you have on the form on this page http://ezrent.lv/lv 

    https://www.jotform.com/71792135678972