function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Peter OrmonPeter Ormon 

odd result from date compare

Can anyone see why this code in an apex class called by a before update trigger would not work correctly?  
The FX_Rate__c object has records current through today and 3 years back for both GBP and EUR.  Yet the Date__c value that it populates is randomly 2 years prior to the selected date. (e.g.objOpp.FX_Rate_Date__c selected is 2017-04-30 yet the Date__c that gets populated is 2015-06-05.)
Code sample below:
list<FX_Rate__c> fxRate = [Select Id, FX_Rate__c,Currency_Code__c, Date__c from FX_Rate__c WHERE Currency_Code__c IN('GBP','EUR') ORDER BY Date__c DESC NULLS LAST];
            for (Opportunity objOpp :oppList)
            {
              if (objOpp.Ticket_Currency__c != 'USD')
             {
                        Date fxDate = objOpp.FX_Rate_Date__c;
                       if (fxRate.size() > 0)
                        {
                            for (FX_Rate__c rate :fxRate)
                            {                                
                                if(fxDate.isSameDay(rate.Date__c)  && objOpp.Ticket_Currency__c  == rate.Currency_Code__c)
                                {
                                    objOpp.FX_Rate__c = rate.Id;
                                    objOpp.FX_Rate_Date__c = fxDate;                                                                     
                                       break;                                       
                                }
                                fxDate = fxDate.addDays(-1);
                            }
                        }
Amil_AbdallahAmil_Abdallah
You have the fxDate variable set to subtract a day from itself inside of a loop. How many records does your fxRate query pull in, because essentially you are subtracting that many days from your fxDate variable, based on the logic you have shown here. 
Peter OrmonPeter Ormon
Thanks for your reply.  I expect the query to return hundreds of records.  However, I break the loop when a match is found for the date and currency code.  Sometimes the date selected my be a later date then the most recent date in the query, so within the loop, I subtract one day until the a date is found.  For instance, if the latest date in the query is 2017-01-01 but the latest record in the object is 2016-12-31, the first time through the loop there would be no match, but the next pass should find a match with 2016-12-31, then break.  This is why I order the query results by date descending so the most recent date is the first processed.  Unless the loop doesn't process the records in the order they are returned.