- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-17-2019 01:40 AM
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
Solved! Go to Solution.
- Labels:
-
Scripting and Coding

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-17-2019 01:49 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-17-2019 01:59 AM
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
Mark ✅ Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-01-2024 04:49 AM
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.