function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
NervosaNervosa 

About SOQL query and date comparing.

Greetings to everybody out there!

So here is the question. There is a SOQL query that being formed like this:

       date mysearchdate=date.valueOf(searchDate);
       string sortFullExp = sortExpression  + ' ' + sortDirection;
       if(searchText != null) {
           searchstr = 'WHERE Name LIKE \'%' + searchText + '%\' order by ';}
       if(searchDate != null) {
           searchstr = 'WHERE Name LIKE \'%' + searchText + '%\' and CreatedDate >=: mysearchdate order by ';}   
           
       items = Database.query('Select id, Name, Item_Price__c, CreatedDate from Item__c ' + searchstr + sortFullExp);

 Well, the main problem is in this -

CreatedDate >=: mysearchdate

part of code. It doesn't work when i need to perform accurate comparison:

CreatedDate =: mysearchdate

Why?

 

Thanks in advance.

Best Answer chosen by Admin (Salesforce Developers) 
NervosaNervosa

Finally I've found an answer! It is SOQL function DAY_ONLY()

 

date mysearchdate=date.valueOf(searchDate);
string sortFullExp = sortExpression + ' ' + sortDirection;
if(searchText != null) {
searchstr = 'WHERE Name LIKE \'%' + searchText + '%\' order by ';}
if(searchDate != null) {
searchstr = 'WHERE Name LIKE \'%' + searchText + '%\' and DAY_ONLY(CreatedDate) =: mysearchdate order by ';}

items = Database.query('Select id, Name, Item_Price__c, CreatedDate from Item__c ' + searchstr + sortFullExp);

All Answers

NervosaNervosa

Well, I guess it's all because of datetime format of system field CreatedDate - it is different with mysearchdate. So here is one more question - can I compare just Day, Month and Year?

NervosaNervosa

Finally I've found an answer! It is SOQL function DAY_ONLY()

 

date mysearchdate=date.valueOf(searchDate);
string sortFullExp = sortExpression + ' ' + sortDirection;
if(searchText != null) {
searchstr = 'WHERE Name LIKE \'%' + searchText + '%\' order by ';}
if(searchDate != null) {
searchstr = 'WHERE Name LIKE \'%' + searchText + '%\' and DAY_ONLY(CreatedDate) =: mysearchdate order by ';}

items = Database.query('Select id, Name, Item_Price__c, CreatedDate from Item__c ' + searchstr + sortFullExp);

This was selected as the best answer