Skip to main content
Known Participant
May 20, 2021
Question

Age calculation that if >6 months show 1 year value

  • May 20, 2021
  • 1 reply
  • 566 views

Hello!

I am looking for a help to understand why the below script does not work the way I would like it to work.

I would like the script to give me below value:

- if age < 1 and month <6  then give me months count with word "month(s)" 

- if age <1 and month >=6, then give me a value of "1 year".

The below code seems to work fine, but does not give a word "month(s)" in the first condition.

Could some help me adjust the code so that it would work?

 

event.value = "";

var dobValue = getField("Textfield-54").value;

if (dobValue!="") {

var dob = util.scand("mm/dd/yyyy", dobValue);

var today = new Date();

var age = today.getTime() - dob.getTime();

// compute age in milliseconds

var nAgeMilliseconds = today.getTime() - dob.getTime();

var nAgeYears = ( age / (1000 * 60 * 60 * 24 * 365.2425) - 0.005);

if(nAgeYears < 1) {

var nAgeMonths = today.getMonth() - dob.getMonth();
if(nAgeMonths < 6)

nAgeMonths += 12;

event.value = Math.floor(nAgeMonths) + " Months";

if(nAgeMonths >= 6)

nAgeMonths = 1;
event.value = Math.floor(nAgeMonths);
}
else

event.value = Math.floor(nAgeYears);

}

This topic has been closed for replies.

1 reply

try67
Community Expert
Community Expert
May 20, 2021

You have to add curly brackets to attach more than one line of code to an if-statement.

Try this:

 

if(nAgeYears < 1) {
	var nAgeMonths = today.getMonth() - dob.getMonth();
	if (nAgeMonths < 6)	{
		nAgeMonths += 12;
		event.value = Math.floor(nAgeMonths) + " Months";
	} else if (nAgeMonths >= 6) {
		nAgeMonths = 1;
		event.value = Math.floor(nAgeMonths) + " Months";
	}
} else {
	event.value = Math.floor(nAgeYears) + " Years";
}

 

Note I didn't check the logic of your code, just fixed the syntax and added the missing strings.

Beata5CBFAuthor
Known Participant
May 20, 2021

Thank you try67, for the fixed syntax, however, it doesn't give me 1 year when there are 6 or more months instead it gives me # of months.

try67
Community Expert
Community Expert
May 20, 2021

Change this:

 

} else if (nAgeMonths >= 6) {
nAgeMonths = 1;
event.value = Math.floor(nAgeMonths) + " Months";
}

 

To:

 

} else if (nAgeMonths >= 6) {
event.value = "1 Year";
}