0

I have a Datetime field in Salesforce called Checkin_Date__c. I have got a list of records, then trying to compare the checkin datetime field in all the records, and want to store the recent one. But it does not seem to compare the the datetime field appropriately.

//allcandidates is a list of records

for(m=0;m<allcandidates.size()-1; m++) {

 System.debug(' m' + allcandidates[m]);  //2019-01-02 04:18:00
 System.debug('m+1' + allcandidates[m+1]); // 2013-02-19 04:19:00

 if(allcandidates[m].Checkin_Date__c <= allcandidates[m+1].Checkin_Date__c)


  {
     System.debug('Condition is true')

   }

The code does not seem to find that one date is greater than other, hence does not enter the if condition. What am I doing wrong.

6
  • Datetime fields are stored in UTC and do support comparisons. Note the values will be displayed in the user timezone. Those points aside, you should consider the possibility that your array/list may have entries with null check-in dates (or even null SObjects). Could this be causing your code to stop before you get to the value you are looking for.
    – Phil W
    May 20 '19 at 15:55
  • 1
    this line System.debug('m+1' + allcandidates[m+1]); and also your if will cause error when you arrive in the last record....
    – m Peixoto
    May 20 '19 at 16:13
  • Where do you get allCandidates from? Is it a query?
    – Adrian Larson
    May 20 '19 at 16:26
  • @mPeixoto the for loop runs for SIZE()-1, so I think there shouldn't be case were it is exceeding the index.
    – Student
    May 20 '19 at 20:51
  • @AdrianLarson yes I am running a query to fetch the records. The query seems to be returning the records fine.
    – Student
    May 20 '19 at 20:54
2

Just add an ORDER BY clause in your query.

List<MyObject__c> records = [
    SELECT ...
    FROM MyObject__c
    WHERE ...
    ORDER BY Checkin_Date__c DESC
];
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.