Skip to main content
All CollectionsForm BuilderForm Scripting & Calculations
Calculating Duration from a Date Field
Calculating Duration from a Date Field
Angela Lim avatar
Written by Angela Lim
Updated over a week ago

If you would like to calculate the number of years or months between two date fields, or a duration between today's date and a date field (such as a person's age based on Date of Birth), you can do so using our scripting language, Lua.

First, make sure that the Date fields you want to calculate on have slugs:

You'll also want to make sure that you have a Numeric field in your form to capture the difference between dates. This Numeric field should also have a slug:

For example, if you wanted to calculate the Age based on a Date of Birth, you would have one Date field slugged date_of_birth  and a Numeric field slugged age .

If you wanted to calculate the number of months between two home visits, you would have two Date fields, slugged home_visit_one  and home_visit_two , and a Numeric field slugged months_between_visits .

Once you have your fields properly slugged and set-up in your form, you can then write your script in the Scripting box.

To calculate the difference between today's date and a date field

If you'd like to compare an entered date with today's date (often to evaluate the age of a person), you can use the syntax below:

answers.age = difftimes(today(), answers.date_of_birth).year 

Where:

  • answers.age  is the slug of the numeric field where you want the duration to be entered

  • difftimes(x, y) signals that you want to calculate the difference between the two dates in the parentheses

  • today()  gets the current Date Time

  • answers.date_of_birth  is the Date field you want to compare to

  • .year indicates what type of time you are looking to calculate: months (entered as .month  or years

To calculate the difference between two date fields

If you have two date fields in your form and you want to get the difference between the two, you can use the syntax:

answers.months_between_visits = difftimes(answers.home_visit_two, answers.home_visit_one).month 

Where:

  •  answers.months_between_visits  is the slug of the numeric field where you want the duration to be entered

  • difftimes(x, y)  signals that you want to calculate the difference between the two dates in the parentheses

  • (answers.home_visit_two, answers.home_visit_one)  are the two Date fields to calculate the difference between, with the latest date as the first entry

  • .month indicates what type of time you are looking to calculate: months or years (entered as .year )


Once you have added your script, click Save Changes.

When you create a new form result and enter in a date or two, the form will automatically calculate the difference.

Did this answer your question?