1

I was trying to convert string to Time datatype in apex, any one help on this would be great.

Salesforce recently come up with new datatypes Time, URL. I was using the Time datatype and am unable to convert string value to Time.

Error:

Illegal assignment from String to Time error

Code:

APS_Treatment__c treat = [SELECT Id, APS_Start_Date__c, APS_Time1__c, 
    APS_Time_1__c FROM APS_Treatment__c WHERE Id = :TreatId]; 

DateTime appTime = treat.APS_Start_Date__c; 
appTime = appTime.addhours(treat.APS_Time_1__c.hour()); 
appTime = appTime.addminutes(treat.APS_Time_1__c.minute()); 
String sd = String.valueOf(appTime.format('hh:mm:ss\'z\'')); 
treat.APS_Time_1__c = sd; 
update treat;
2
  • You would need to first convert string to date time then add time, or there is also new instance method? Could you update your question with some code snippet?
    – Raul
    Oct 19, 2017 at 9:01
  • APS_Treatment__c treat = [SELECT Id,APS_Start_Date__c,APS_Time1__c, APS_Time_1__c FROM APS_Treatment__c WHERE Id=:TreatId]; DateTime appTime = treat.APS_Start_Date__c; appTime = appTime.addhours(treat.APS_Time_1__c.hour()); appTime = appTime.addminutes(treat.APS_Time_1__c.minute()); String sd = String.valueOf(appTime.format('hh:mm:ss\'z\'')); treat.APS_Time_1__c = sd; Update treat; Oct 19, 2017 at 9:21

1 Answer 1

5

You can use Time.newInstance method to construct the Time from Date time:

Example:

DateTime dt = System.today();
Time myTime = Time.newInstance(dt.hour(), dt.minute(), dt.second(), dt.millisecond());

Your code needs to be modified as:

APS_Treatment__c treat = [SELECT Id, APS_Start_Date__c, APS_Time1__c, 
    APS_Time_1__c FROM APS_Treatment__c WHERE Id = :TreatId]; 

DateTime appTime = treat.APS_Start_Date__c; 
treat.APS_Time_1__c = 
    Time.newInstance(
        appTime.hour(), 
        appTime.minute(), 
        appTime.second(), 
        appTime.millisecond()); 
update treat;
3
  • Thanq for Quick reply.When a record is created from IOS Mobile, Time is saving in UTC. But wen i see it in sfdc the time is in GMT. I want to make the Time field is same in both IOS app and Desktop. Oct 19, 2017 at 12:22
  • Your query is not related to your original question. Please log a new one if you are unable to find it, and do not forget to accept the best answer to help others looking for same problem.
    – Raul
    Oct 19, 2017 at 12:34
  • This answer might solve the question author problem, but does not answer how to convert string to a Time object in the absence of valueOf() method
    – sskular
    Feb 3, 2021 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.