Level 1

0% to

Level 2

Tip /

to gain points, level up, and earn exciting badges like the new
Mission!

View all

Script to calculate number of days between 2 dates

Level 3

I'm fairly new to scripting and have looked for an answer to this; I have found some posts though have been unable to apply them to my scenario.

I have one date that is automatically populated with the current date, and another (earlier) date that the user enters. I need to have a field which calculates the difference between these 2 dates in days.

Any help appreciated - I'll use any help as a learning exercise!

0 Replies

Employee

Here some links around this subject:

Create a date field or entry

Then a calculated readonly date field

In the calculate event of the second field set FormCalc and place the following code:

if (DateField1.rawValue ne null)then
Abs(Date2Num(DateField1.formattedValue, DateFmt(2)) - Date())
else
\$.rawValue = ""
endif

And the result is:

Level 3
Thanks for this reply. In your example you have a date field, and a second calculated field where the number of days is displayed. What I am trying to do however is to calculate the difference between 2 date fields, and display it in a 3rd field. Any suggestions for this?

Level 4

ok, then a slightly changed form

Datefield2 without pre-population in initialize

# of days calculated with slightly modified script

if (DateField1.rawValue ne null and DateField2.rawValue ne null)then
Abs(Date2Num(DateField1.formattedValue, DateFmt(2)) - Date2Num(DateField2.formattedValue, DateFmt(2)))
else
\$.rawValue = ""
endif

Level 3
Do I paste that script into the script editor for the 3rd box? Date 1 is auto-populated and date 2 is user-entered.

Level 4
yes, the calculate script is for the 3rd field. Date 1 gets iinitialized with today's date date 2 is empty. Make sure that it is Event calculate and FormCalc as language

Level 3
Thanks for that! But with a current date of 28 August 2020 and an field 2 date of 26 August 2020, I get a calculated number of days of 44,068!

Employee

Level 3
It works on your PDF, but if I copy that subform into my document, it gives a number in the 44,000's ?

Level 4
that may be your locale and date formats which do not match. I used English USA.

Level 3
Many thanks, that fixed it! One more question - how can I change the way the date displays in the boxes? Instead of Aug 31, 2020, I would like it to display Monday August 31, 2020. If I change it, then the calculation no longer works. Do I need to change it in specific areas?

Level 4

Regarding the change of output format make the following changes:

Set the Data pattern of your 2 date fields to

and the Display pattern to the one you wish to have

Change the calculation script (if you use mine in FormCalc) to

What this does is to use the data format of your fields to get the date values for calculation which stays fixed whereas your display format can then change because we do not use the formattedValue properties any more.