Skip to main content
Participant
September 30, 2021
Question

Date calculation

  • September 30, 2021
  • 1 reply
  • 386 views

I would like a calculation of 2 date input which only gives gives me the year difference in whole year on the 2 inputs.
The inputs have the format [dd-mmm-yyyy] and the script shown below also seems OK for that, but I have 2 more wishes that I would like the calculation to perform.
If the inputs are only entered in the format [yyyy], it must also be able to calculate the difference throughout the year, and if one or both inputs are not of the formats [dd-mmm-yyyy] or [yyyy], the output must be blank (nothing).

Please help me with what the calculation should look like to fulfill my wishes.

 

// Custom calculate script
(function () {

var sStart = getField("Dato5").valueAsString;
var sEnd = getField("Dato6").valueAsString;
var dStart, dEnd, diff;

if(sStart && sEnd) {
dStart = util.scand("dd-mmm-yyyy", sStart);
dEnd = util.scand("dd-mmm-yyyy", sEnd);
diff = dEnd.getTime() - dStart.getTime();
event.value = Math.floor(diff / 31536e6) + " år";
} else {
event.value = "";
}

})();

This topic has been closed for replies.

1 reply

try67
Community Expert
Community Expert
September 30, 2021

Try this:

 

 

(function () {

event.value = "";
var sStart = getField("Dato5").valueAsString;
var sEnd = getField("Dato6").valueAsString;
var dStart, dEnd, diff;

if(sStart && sEnd) {
	dStart = util.scand("dd-mmm-yyyy", sStart);
	dEnd = util.scand("dd-mmm-yyyy", sEnd);
	if (dStart && dEnd) {
		diff = dEnd.getTime() - dStart.getTime();
		event.value = Math.floor(diff / 31536e6) + " år";
	} else {
		dStart = util.scand("yyyy", sStart);
		dEnd = util.scand("yyyy", sEnd);
		if (dStart && dEnd) {
			diff = dEnd.getTime() - dStart.getTime();
			event.value = Math.floor(diff / 31536e6) + " år";
		}		
	}
}})();

 

Helge5EFBAuthor
Participant
September 30, 2021

It's comming op an error message: Syntax Error: syntax error 22: at line 23

If the date inputs are not correct ([dd-mmm-yyyy] or [yyyy]) will it come up with a blank field (output)?

try67
Community Expert
Community Expert
September 30, 2021

Fixed it above now.

And yes, the field will be blank if you enter something in a different format.