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
Srikar Reddy Srikar KSrikar Reddy Srikar K 

how to convert string 10:10 AM to time in apex

Hi, 
I have string value 10:10 AM and I want to set it to a field of type Time.
Didn't find the right code for this in community.
Please help.

Thank you,
Srikar
VinayVinay (Salesforce Developers) 
Check below example.

https://www.forcetalks.com/salesforce-topic/how-to-convert-string-date-format-in-salesforce-apex/

Thanks,
ravi soniravi soni
Hi Srikar,
try this following code
string sTime = '10:10';
 String[] strTimeSplit = sTime.split(':');
 Time timeChange = Time.newInstance( Integer.valueOf(strTimeSplit[0]) //hour
                                     ,Integer.valueOf(strTimeSplit[1]) //min
                                     ,0                                //sec
                                     ,0);
                                   system.debug('timeChange==> ' + timeChange);
I am sure it will help you. let me know and close your query by marking it as solved.
SwethaSwetha (Salesforce Developers) 
HI Srikar,
Your ask seems similar to https://salesforce.stackexchange.com/questions/148660/deserializing-a-string-from-json-to-datetime-in-apex-yields-invalid-format-err You might want to try the approach of using DateTime.parse('11/6/2014 10:10 AM')

If this information helps, please mark the answer as best.Thank you
Malika Pathak 9Malika Pathak 9

Hi Srikar,

String timee = '10:10 a';
DateTime dt = Datetime.now();
String strTimeInAMorPM = dt.format(timee);
system.debug('Time : '+strTimeInAMorPM);

For more REFERENCE find the below link...

https://www.salesforcecodecrack.com/2020/04/format-dates-and-time-using-apex-in.html

if you find this helpful mark it as the best answer.

Srikar Reddy Srikar KSrikar Reddy Srikar K
Hi All,
Thank you for the quick response. The problem is the above mentioned code working when the string contains '10:10' or '10:10 a', but the problem here is we are getting the value as '10:10 AM' in the JSON. we need to read that and covert to time format and set it in the field which is of time.

Thank you,
Srikar
Om GuptaOm Gupta
Hi srikar reddy , you can use this code
String timeStr = '3:14 AM';
String[] splitTime = timeStr.split(' ');
String[ ] splitTime2 = splitTime[0].split(':');
String timeFormated = (splitTime[1].indexOf('PM') != -1 ? (Integer.valueOf(splitTime2[0])+10)+'' : (splitTime2[0]))+':'+splitTime2[1];
System.debug('>>>>>>>>>>>>'+timeFormated);
String inputDate = System.now().format('yyyy-MM-dd');
inputDate += ' '+timeFormated;
System.debug('>>>>>>inputDate>>>>>>'+inputDate);