I am trying to delete records from last one year created records using a batch class. How can I query record whose
CreatedDate spans from the current date to last one year?
You can use Date Literals:
For deleting records of last year:
delete [SELECT Id FROM Opportunity WHERE CreatedDate = LAST_YEAR];
For all records not created this year:
delete [SELECT Id FROM Opportunity WHERE CreatedDate != THIS_YEAR];
With this, you do not have to worry about manipulating with date/year separately.
Integer year = Date.today().year() - 1; Date todaysDate = Date.today(); List<Contact> contactList= [SELECT id FROM Contact WHERE CALENDAR_YEAR(CreatedDate) =: year AND DAY_ONLY(CreatedDate) =: todaysDate];
refer these date time functions and mold the SOQL query as per your requirment.