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
Amoolya DontyAmoolya Donty 

Query Date field from DateTime field in SOQL

Hi,

I need to query date field from a Date/Time field in a SOQL query.

EG: [SELECT Id,StartDate FROM XYZ WHERE StartDate >=: StartTime];

StartDate = Date type
StartTime = Date/Time type


 I need to query the date in YYYY-MM-DD format, but in Date field the value being stored is YYYY-MM-DD HH:MM:SS format. So i cannot able to fetch the values.
 
Best Answer chosen by Amoolya Donty
Ray C. KaoRay C. Kao
A working code:

Datetime dt = System.now();
Date d = dt.Date();
List<Opportunity> opp = [ SELECT Id,Datefield__c FROM Opportunity WHERE Datefield__c = :d ];
System.debug(opp.size());

Where Datefield__c is a Date type field

All Answers

Amoolya DontyAmoolya Donty
Here I am fetching Date from DateTime and storing it in a String
String test = Datetime.now().format('yyyy-mm-dd');
system.debug('test **********'+test); Output : 2015-04-15
Date test1 =  Date.valueOf(test);
system.debug('test1'+test1); Output : 2015-04-15 00:00:00

If i pass test variable to compare Startdate(StartDate >=: test), then i am getting error: "Invalid bind expression type of String for column of type Date"
sandeep sankhlasandeep sankhla
Hi Amoolya,

Please refer below link for more details..
https://developer.salesforce.com/forums/ForumsMain?id=906F00000008wFbIAI

You can simply convert the date tiem field to date feild and then you can do comparisin..

Please check with this and let me know if you need naything..
P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 
 
Amoolya DontyAmoolya Donty
Hi sandeep,
I tried converting datetime to date and passing converted value to a query. But still im not getting the values
sandeep sankhlasandeep sankhla
Did you check the above link, which I haev shared ?
you can get the day , date adn month from datetime field then you can pass them to date method to cerate a date and then you can compare them...

Thnaks
 
Ray C. KaoRay C. Kao
A working code:

Datetime dt = System.now();
Date d = dt.Date();
List<Opportunity> opp = [ SELECT Id,Datefield__c FROM Opportunity WHERE Datefield__c = :d ];
System.debug(opp.size());

Where Datefield__c is a Date type field
This was selected as the best answer