Friday 18 February 2022

Fetch the greatest/Max/Min date from the list

As we have scenario to fetch greater date value from the multiple objects like I have to find greatest createddate from 2-3 contacts data so that this date can be used further.  


Lets consider the scenario on contact objects.


List<DateTime> listCreatedDates = new List<DateTime>();
List<Contact> cons = [select id, CreatedDate from Contact limit 2];

For(Contact c : cons) {
    listCreatedDates.add(c.CreatedDate);
} listCreatedDates.sort(); DateTime minDate = listCreatedDates.get(0);
DateTime maxDate = listCreatedDates.get(listCreatedDates.size()-1);
System.debug('minDate : ' + minDate );
System.debug('maxDate : ' + maxDate );


Lets discuss about the above code:

Output for me - 
List<Contact> cons = [select id, CreatedDate from Contact limit 2];
Contact result to get minimum greatest, maximum and minimum date from the list by apex.


minDate : 2020-02-06 07:59:15
maxDate : 2020-07-18 13:23:36

0 comments:

Post a Comment

If you have any doubts, please let me know.