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

Sebastian R_
Kilo Sage

You can use plain javascript for it (https://stackoverflow.com/a/7143443)

array.reduce(function (a, b) { return a > b ? a : b; });

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

Hello Omkar,

I tried the mentioned script and it worked perfectly, however, I had to change the format of the dates to yyyy/MM/dd.

 

Thank you for the help.

-Prabhh

Hi 

I'm sorry for that, here is the code that would work with your format - 

 

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

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