-
Notifications
You must be signed in to change notification settings - Fork 45
Calculating Values with Dates
Matthew Hall edited this page Mar 21, 2023
·
19 revisions
The following is an example of calculating the number of days between two dates.
Number of days between two dates
Here is the code you will need:
const date1String = data.startDateTime; // date string 1, change "startDateTime" to the name of your first date field
const date2String = data.endDateTime; // date string 2, change "endDateTime" to the name of your second date field
const date1 = new Date(date1String); //changes the data types from strings to dates
const date2 = new Date(date2String);
// Calculate the difference between the two dates in milliseconds and converts the date to a number
const diffInMs = date2 - date1;
// Convert the difference in milliseconds to days
const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24));
value = diffInDays; // assigns the calculated number of days to the value that will be displayed in the field
For the text field that you want the calculated number of days between two dates to show on, perform the following steps:
- Go into the field setting, on the data tab, expand the calculated values section, and past the code above into the javascript section.
- The only thing you should have to change to make this work is to make sure that the names of your two Date Time fields match ones in the javaScript code (
startDateTime
andendDateTime
). To set those names go to the API tab of the settings for each Date Time field. - Save your form design and try it out in the preview mode.
Note for developers: It appears that the data type for the Date/Time field that returns with data.dateTime is a string. So it first has to be converted back to a date before you can simple subtract the two dates and take advantage of javaScript's automatic converting from date to number.