+ Start a Discussion
Ramana123Ramana123 

2.Create a field called OldDate(Date field) on contact. Write a batch to get the contacts whose OldDate is 5 days older than currentdate and Delete those contacts.

Below code is not working can anyone help me in this...?

global class Date_Batch_Class implements Database.Batchable<sObject>{

        global Date_Batch_Class(){
                   // Batch Constructor
        }
       
        // Start Method
        global Database.QueryLocator start(Database.BatchableContext BC){
        
            string query = 'select id,LastName from Contact where OldDate__c = LAST_N_DAYS:5';
               System.debug('aaaaaaaaaaaaaaaaaaaaaaaa'+query) ; 
            return Database.getQueryLocator(query);

        }

      
      // Execute Logic
       global void execute(Database.BatchableContext BC, List<Contact>scope){
             
        delete scope;
     
       }
     
       global void finish(Database.BatchableContext BC){
            // Logic to be Executed at finish
       }
    }
Sachin HoodaSachin Hooda
string query = 'select id,LastName from Contact where OldDate__c = LAST_N_DAYS:5';
This query will work for contacts whose Old date is within the last 5 days. 
Since you need contacts which have Old date value as you mentioned should be 5 days older. You need to change the query to,
string query = 'select id,LastName from Where OldDate__c < LAST_N_Days:5';
This will query only those records which has Old date value older than 5 days, equal to 5 days wont be counted.