1

I am trying to write a query which returns data from 3 months back and bases the current month from the system time. So if the query ran today, it would return May data. Something like:

List<testing> myList = [select id, name.....from .... where month__c = 3_MONTHS_AGO ...]

Is there a nice way of doing this in Apex?

1 Answer 1

7

You can get the month to use in your filter as follows:

Integer target = Date.today().addMonths(-3).month();

So your filter would be:

WHERE Month__c = :target

Or you could just inline it:

WHERE Month__c = :Date.today().addMonths(-3).month()

If you have a Date or Datetime field, you can use Date Functions:

WHERE CALENDAR_MONTH (DateField__c) = :target
2
  • This is working well! Awesome. I used the CALENDER_MONTH way.
    – Angelo
    Aug 22, 2016 at 20:17
  • 1
    You could also use the SOQL Date Literals Month__c = LAST_N_MONTHS:3 AND Month__c != LAST_N_MONTHS:2. That's pretty clunky though...
    – Derek F
    Aug 22, 2016 at 20:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .