1

Say I have a query that goes something like this:

Currency_Exchange_Rates__c cerRec = [SELECT Currency_Code__c, Exchange_Rate_Period__c, Exchange_Rate__c
FROM Currency_Exchange_Rates__c 
WHERE Currency_Code__c = :c.Currency__c 
AND THIS_MONTH = CALENDAR_MONTH(Exchange_Rate_Period__c)
AND THIS_YEAR = CALENDAR_YEAR(Exchange_Rate_Period__c) LIMIT 1];

This returns an error:

expecting a colon, found 'CALENDAR_MONTH'

A little research reveals that you can't actually compare the result of a Date function with a Date literal in the WHERE clause (see Notes at bottom of this page)

So Salesforce has clearly documented that I can't do this, but I can't figure out how to work around this limitation? Seems like a pretty common use case - how can I best filter out SOQL records where I need to compare a date field to a current date?

2

Found the answer in code I had previously written -_-

Rather than use SOQL's date literals like TODAY, instead use Apex class functions that provide the same thing. In this case, I used a combination of the today(), month(), and year() functions of the Date class:

Currency_Exchange_Rates__c cerRec = [SELECT Currency_Code__c, Exchange_Rate_Period__c, Exchange_Rate__c 
FROM Currency_Exchange_Rates__c 
WHERE Currency_Code__c = :c.Currency__c 
AND CALENDAR_MONTH(Exchange_Rate_Period__c) = :Date.Today().month()
AND CALENDAR_YEAR(Exchange_Rate_Period__c) = :Date.Today().year()
LIMIT 1]; 
0

You can use for specifically data

Date dte = CALENDAR_MONTH(Exchange_Rate_Period__c);

List<Account> acc = [Select Id, Name From Account Where CreatedDate =: dte ];

Let me know if you faced issue with this also.

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.