Skip to main content
Inspiring
March 9, 2023
Question

Calculate the difference in years between two dates

  • March 9, 2023
  • 2 replies
  • 1388 views

Hi
I have 4 fields named year1, year2, year3, year4 respectively.
I want to calculate the difference in years with respect to the dates entered respectively in "HIRES1", "HIRES2", ASSUNCTION3, ASSUNCTION4.
In the calculation script of each field I have inserted this formula

var s1 = this.getField("HIRES1").value;date = util.scand("mm/dd/yyyy",s1);now = new Date();difference_in_years = (now.getFullYear()) - date. getFullYear();if (now.getMonth()<date.getMonth()) {difference_in_years--;} else if ((now.getMonth()==date.getMonth()) && (now.getDate()<date .getDate())) {difference_in_years--;}event.value = difference_in_years;

The formula works to calculate the years starting from the date inserted in "ASSUNCTION1", while for the other fields the console gives me this error message

TypeError: date is null
1:Console:Exec
undefined

Anyone who can help me solve this problem?
Thank you

This topic has been closed for replies.

2 replies

Thom Parker
Community Expert
Community Expert
March 9, 2023

First, when you post code, please format it so it can be read. 

The "util.scand" function returns null when it is given a date string that does not match the format provided. So, the date fields that are showing this error, must not be formatted correctly.  

Add a "console.println()" statement to the code to display the input date string.

 

 

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
Bernd Alheit
Community Expert
Community Expert
March 9, 2023

Where does you use the field "ASSUNCTION1"?

ENE5CD9Author
Inspiring
March 9, 2023

sorry
the field is HIRES1 not ASSUNCTION1