[SalesForce] Deserializing a string from JSON to DateTime in Apex yields “Invalid format” error

I have a string as,

field name : start Date: 2016-11-14 08:00 AM ( string type)

how to convert this to Date time. I tried Date.parseDate and below option also.

String val = recruiters[j].Start_Time_Formula__c; 
                            system.debug('val ::'+ val);
                            DateTime date1 = (DateTime)Json.deserialize('"'+val+'"', DateTime.class);
                            system.debug('date1 ::' + date1);

but I am getting error as,

System.JSONException: Invalid format: "2016-11-14 08:00 AM" is malformed at " 08:00 AM": (System Code)

I referred the below link and got with the above error.

Convert String DateTime to User Locale Date Time

any help ?

Best Answer

You must use an ISO 8601 date, specifically something like:

2016-10-30T15:27:02.000Z

Which is October 30th, 2016, at 3:27 pm (+2 seconds) in Greenwich Mean Time.

To parse dates in the user's locale, use the appropriate form for the user. For example, in the United States, we would write:

10/30/2016 3:27 pm

Carefully note the order of month, day, and year, and pay attention to the separator (/). You need to input the date exactly as salesforce shows dates to you, because it is locale dependent.