how to get a latest date from an array

Prabhh
Kilo Guru

Hello,

Can any one please suggest a solution to get a latest date from an array of dates using server side code? The array of dates is as per the below format:

var array = ["2019-08-28","2019-08-29","2019-09-06"];

Expected output: 2019-09-06

 

- Prabhh

1 ACCEPTED SOLUTION

Omkar Mone
Mega Sage

Hi 

Try this below code in background script - 

function max_date(all_dates) {
var max_dt = all_dates[0],
  max_dtObj = new Date(all_dates[0]);
all_dates.forEach(function(dt, index)
  {
  if ( new Date( dt ) > max_dtObj)
  {
  max_dt = dt;
  max_dtObj = new Date(dt);
  }
  });
 return max_dt;
  }

gs.print(max_date(["2019/08/28","2019/08/29","2019/09/06"]));

 

Let me know if it helps.

 

Regards,

Omkar Mone

View solution in original post

6 REPLIES 6

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Prabh,

use below script in background or any server side and it will work

var array = ["2019-08-28","2019-08-29","2019-09-06"];

// consider the first element of array as latest
var latest = array[0];

for(var i=0;i<array.length;i++){

// if the date coming from array position is ahead then set latest to this array element
if (GlideDateTime(array[i]) > GlideDateTime(latest))
latest = array[i];

}

gs.info('Latest date is: ' + latest);

scree shot below

find_real_file.png

find_real_file.png

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Appanna M
Tera Guru

Hello @Prabhh ,

 

Try the below logic.

// Define an array of GlideDateTime objects
var dateArray = [
    new GlideDateTime("2023-01-15 12:00:00"),
    new GlideDateTime("2024-05-20 08:30:00"),
    new GlideDateTime("2022-11-01 14:45:00"),
    new GlideDateTime("2024-05-21 10:00:00")
];

var highestDate = dateArray[0];

for (var i = 1; i < dateArray.length; i++) {
    if (dateArray[i].after(highestDate)) {
        highestDate = dateArray[i];
    }
}
gs.debug('The highest date is: ' + highestDate);

 

Please Mark My Answer as Helpful and Accept as Solution, if you find this article helpful or resolves your issue.