Skip to main content
Known Participant
September 14, 2021
Answered

Compare three date fields and and select the latest date.

  • September 14, 2021
  • 2 replies
  • 1088 views

Can someone assist with a calculation script that complares three different date fields and then returns the latest date of the three? Thanks!

This topic has been closed for replies.
Correct answer Nesa Nurani

Are you getting 3 dates from fields?

Here is example(change field names to your actual field names):

var date1 = this.getField("Date1").valueAsString;
var date2 = this.getField("Date2").valueAsString;
var date3 = this.getField("Date3").valueAsString;

var d1 = util.scand("mm/dd/yyyy", date1);
var d2 = util.scand("mm/dd/yyyy", date2);
var d3 = util.scand("mm/dd/yyyy", date3);
var n1 = d1.getTime();
var n2 = d2.getTime();
var n3 = d3.getTime();
var h = Math.max(n1,n2,n3);
if(date1 == "" || date2 == "" || date3 == "")
event.value = "";
else if(h == n1)
event.value = date1;
else if(h == n2)
event.value = date2;
else if(h == n3)
event.value = date3;

2 replies

Nesa Nurani
Community Expert
Nesa NuraniCommunity ExpertCorrect answer
Community Expert
September 14, 2021

Are you getting 3 dates from fields?

Here is example(change field names to your actual field names):

var date1 = this.getField("Date1").valueAsString;
var date2 = this.getField("Date2").valueAsString;
var date3 = this.getField("Date3").valueAsString;

var d1 = util.scand("mm/dd/yyyy", date1);
var d2 = util.scand("mm/dd/yyyy", date2);
var d3 = util.scand("mm/dd/yyyy", date3);
var n1 = d1.getTime();
var n2 = d2.getTime();
var n3 = d3.getTime();
var h = Math.max(n1,n2,n3);
if(date1 == "" || date2 == "" || date3 == "")
event.value = "";
else if(h == n1)
event.value = date1;
else if(h == n2)
event.value = date2;
else if(h == n3)
event.value = date3;

Known Participant
September 14, 2021

Thank you so much!!

BarlaeDC
Community Expert
Community Expert
September 14, 2021

Hi,

 

var Date1 = this.getField("Date1").value;
var Date2 = this.getField("Date2").value;
var Date3 = this.getField("Date3").value;
// this will not work if any of the dates are empty.
Date1 = util.scand("dd-mm-yyyy", Date1);
Date2 = util.scand("dd-mm-yyyy", Date2);
Date3 = util.scand("dd-mm-yyyy", Date3);

if ( Date1 >= Date2 && Date1 >= Date3) {
return Date1;
} else if ( Date2 >= Date1 && Date2 >= Date3){
return Date2;
} else 
return Date3;
}

 

You will need to change the date field names to match your form, and it also allows being equal to, as you didn't mention what happens in that area.

 

I have also assumed that the date is in the format dd-mm-yyyy, if not you will need to change that too.

 

But this should be a good starting point.

Known Participant
September 14, 2021

Thank you for the quick reply! Definately a good starting point. Nesa's script did the trick.