+ Start a Discussion
Tony66Tony66 

SOQL query logic for date condition in Apex controller

On a visual-force page of a workorder record, I've to display list of workorders created for the same location where the createddate is within the last 30 days of the creationdate of the current record.
For ex: If the current record was created on Jan 31st for a location A, I want to display all the workorders that were created from Jan 1st to 31st for location A.

This is the query I've but it obviously displays records created in last 30 days but not the records created in last 30 days of createddate of the current record. How can I modify my query?
CWOs=[SELECT Id, Status, location.Name, createddate FROM WorkOrder WHERE location.Name = : getwo().location.Name and id != : getwo().id and recordtype.name = 'Child' and createddate = LAST_N_DAYS:30 ORDER BY CreatedDate asc];

 
Best Answer chosen by Tony66
Danish HodaDanish Hoda
Hi Tony,
You will have to query it twice, firstly you need to query for the createdDate, and get the date variable as:
Date dateVar = workOrderObj.CreatedDate.addDays(-30);
then you can use the query you need to fetch the records for as below:
CWOs=[SELECT Id, Status, location.Name, createddate FROM WorkOrder WHERE location.Name = : getwo().location.Name and id != : getwo().id and recordtype.name = 'Child' and createddate > :dateVar ORDER BY CreatedDate asc];
 

All Answers

ANUTEJANUTEJ (Salesforce Developers) 
Hi Tony,

Have you tried choosing the records where the codition is created_date-30 so that only those records are selected which are 30 days from creating date.

Regards,
Anutej
Danish HodaDanish Hoda
Hi Tony,
You will have to query it twice, firstly you need to query for the createdDate, and get the date variable as:
Date dateVar = workOrderObj.CreatedDate.addDays(-30);
then you can use the query you need to fetch the records for as below:
CWOs=[SELECT Id, Status, location.Name, createddate FROM WorkOrder WHERE location.Name = : getwo().location.Name and id != : getwo().id and recordtype.name = 'Child' and createddate > :dateVar ORDER BY CreatedDate asc];
 
This was selected as the best answer
Tony66Tony66
Hello Danish, I'm getting a null pointer exception error. 
Danish HodaDanish Hoda
hi Tony,
May I know on which line?
Tony66Tony66
Hello Danish, Nevermind. It seems to be working. Thanks for your help.