I am trying to calculate the hours between 2 time fields, please see below.
I have been using the following javascript and it's not calculating - can anyone please provide any assistance, or a different fomula
const startDate = moment(data.startTime) const endDate = moment(data.endTime) value = startDate.diff(endDate, 'hour')
Hi Linda,
From your screenshot, it seems that your “time components” are nested inside a data grid. When working within a data grid, you’ll need to use the row
variable instead of the data
variable to access responses to other questions within the same row.
Using the data
variable would cause your calculation to fail because it doesn’t specify which row in the data grid to reference. You likely noticed red lines under your expression, indicating an error.
Here’s the updated JavaScript code that should work:
const startDate = moment(row.startTime) const endDate = moment(row.endTime) value = startDate.diff(endDate, 'hour')
Hi Linda,
From your screenshot, it seems that your “time components” are nested inside a data grid. When working within a data grid, you’ll need to use the row
variable instead of the data
variable to access responses to other questions within the same row.
Using the data
variable would cause your calculation to fail because it doesn’t specify which row in the data grid to reference. You likely noticed red lines under your expression, indicating an error.
Here’s the updated JavaScript code that should work:
const startDate = moment(row.startTime) const endDate = moment(row.endTime) value = startDate.diff(endDate, 'hour')
my next issue is trying to calculate all hours - anyone have any ideas? The script I am using is dropping all hours into the text field component - was wondering if there is a way to accumulate all hours??
Hi Linda,
In your screen shot it looks like you are summing a bunch on text fields which is why you are getting a long string which is simply concatenating the text. In this specific scenario I think what you want is to calculate the total hours based on the start and end times of each row within a data-grid. We can achieve this with a JavaScript expression like the one below:
Note that you will need to adapt this JavaScript to match your specific form.
value = _.sumBy(data.dataGridRepeatingTable, (r) => { const startDate = moment(r.startTime) const endDate = moment(r.endTime) return startDate.diff(endDate, 'hour') })
Hi Erin,
Thanks for the info, I was seeing if it was possible to tally up all hours in each row in a total box sitting out of the table - does that make sense??
Hi Linda,
That’s what the example provided is trying to achieve. Though the expression may need to be adapted for your specific form.
I also suggest watching the video below which covers this topic :)