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
thecrmninjathecrmninja 

how do i cast an object result from a dynamic query to a datetime variable?

One of the SFDC bloggers I often follow,  Perspectives on Salesforce,  recently posed the following question: how do i cast an object result from a dynamic query to a datetime variable?

 

Well, here is how I did it.  In this instance, I have a Lead Distribution System.  This controller evaluates the volume of Leads that a user is able to pull on a daily basis, tracking values like languages spoken, extra leads allowed for the day, etc.  One variable it tracks, is the last day the User pulled.  

 

(I've only included the query and the setting of variables as well as me casting to a list by calling those variables, including Date).

 

 

//Call all the values to an object instance, to then be passed to variables public User usr = [Select TruePerDiem__c, LeadPullQueues__c, PerDiem__c,Last_Pulled__c,Open_Leads_Owned__c,PulledXDaysAgo__C, Lang1__c, Lang2__c, Lang3__c, Lang4__c, Lang5__c from User where Id = :userinfo.getuserid() LIMIT 1]; //Create variables to receive dynamic values from above query public String Queue = usr.LeadPullQueues__c; public Double NewMAX= usr.PerDiem__c; public Integer NewDiem = newMax.intvalue(); //LOOK HERE - This is where I am pulling date!!!! Public Date LastPulled = usr.Last_Pulled__c; //Here is where I cast to a list with a SOQL Query, using dynamic variables from above //(please note, I removed alot of the variables I create in my controller for the sake of brevity. List<Lead> leads = [select Id,ownerid,PulledYes__c,ELPLang__c,Priotizer__c from lead where ownerid = :Queue AND (ELPLang__c LIKE :Lang1 OR ELPLang__c LIKE :Lang2 OR ELPLang__c LIKE :Lang3 OR ELPLang__c LIKE :Lang4 OR ELPLang__c LIKE :Lang5)

 

Now, in my example, I use the LastPulled Date Variable for ternary, if/else logic but it could easily be applied to a SOQL statement.  ("...where Date = :LastPulled).

 

Does anybody else have any examples of other approaches.  This really is a great opportunity to learn about dynamic queries, a rich capability of Apex.

 

 

Best Answer chosen by Admin (Salesforce Developers) 
hemmhemm

Thanks, I appreciate the response.  However, I was actually asking about dynamic queries using dynamic apex.  Those queries return generic sObjects and the .get() method retrieves a generic object.

 

After taking a night to sleep on it, I saw my issue.  Turns out is was a silly cut/paste error on my part.

 

This is how you do it.

 

 

List<sObject> sos = Database.query('select id, LastModifiedDate from Account limit 1'); Datetime d = (datetime)sos[0].get('LastModifiedDate');