Skip Navigation

[Resolved] Calculate difference between two dates and save it into a third field.

This support ticket is created 6 years, 7 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
- 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 -
- 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 -

Supporter timezone: Europe/London (GMT+00:00)

This topic contains 1 reply, has 2 voices.

Last updated by Nigel 6 years, 7 months ago.

Assisted by: Nigel.

Author
Posts
#627930

I have a form with 3 fields:

Date From
Date To
and Duration

I need to calculate the duration and save it in the "duration" field.
I would like to be able to display it in years.

Ideally I would like this to happen before saving.

#628179

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi Adrian

If you want to do this before saving the form, I guess you mean before submitting it so the user can see the duration straight away, and that means using JavaScript.

I suggest you use the browser dev tools to examine the form date fields as you update them.

You should see that the actual fields for the dates are hidden fields. The visible datepicker fields are "fake" fields which, when completed, trigger some JS that calculates the UNIX timestamp from the inputted date and adds this to the hidden field.

So, you can add some JS that is triggered by the second date field losing focus which takes the timestamp values from the hidden fields and subtracts them to get the duration, then use the Date function and getFullYear method to convert the difference to years to store in another field.

Is that enough for you to go on?

Let me know if you need more help.