[SELECT Id,Name FROM Account WHERE createddate=THIS_MONTH]

This query is working fine when it is called from button, but it is unable to filter according to the created date when it is invoked from a batch apex.


Based on the test below, the THIS_MONTH date literal does work in batch Apex.

I took your code (that I presume is a contrived example) and added debug log output:

global class  RunBatch implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC){
        string query='select id from Account';
        return Database.getQueryLocator(query);
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        list<id> accIds=new list<id>();
        for(sObject s : scope){
            Account acc=(Account)s;
        list<Account> accList=[select id,name FROM Account
                WHERE createddate=THIS_MONTH AND id IN : accIds];
        System.debug('list=' + accList);
    global void finish(Database.BatchableContext BC) {

and ran it from the Developer Console:

Database.executeBatch(new RunBatch(), 10);

and got the expected output (of 2 Accounts I just created):

list=(Account:{Name=New Account, Id=001i000000wF4mPAAS}, Account:{Name=New Account 2, Id=001i000000wF4o6AAC})

| improve this answer | |
  • so is this a bug or feature(salesforce point of view)?? – asitm9 Jun 30 '14 at 6:22
  • @asitm9 I'm saying I could not find a problem in the code you posted - it worked. – Keith C Jun 30 '14 at 8:44
  • actually i am invoking the batch using a scheduler. – asitm9 Jun 30 '14 at 13:52

Instead of this month can you use

Date monthStart = System.today().toStartOfMonth();
Date monthEnd = System.today().addMonths(1).toStartOfMonth().addDays(-1);

and then in query:

where CreatedDate >= :monthStart and CreatedDate <= :monthEnd
| improve this answer | |

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.