Skip Navigation

[Résolu] Calculate difference between two dates and save it into a third field.

This support ticket is created Il y a 6 années et 8 mois. 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.

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)

Ce sujet contient 1 réponse, a 2 voix.

Dernière mise à jour par Nigel Il y a 6 années et 8 mois.

Assisté par: Nigel.

Auteur
Publications
#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

Les langues: Anglais (English ) Espagnol (Español )

Fuseau horaire: 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.