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 ?

  • sfdcfox

    sfdcfox Correct answer

    5 years ago

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


    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.

    Hi, I have two fields in this case one is text which holds 08:00 AM and other fields is a formula fields ( whichi is combination of today date with text field) which gives the result as 2016-11-14 08:00 AM. I am trying to compare this with salesforce Datetimeformat which is like 2016-11-14 22:52:59. As my formula field format is different, its not allowing me to compare. how to handle it

    Solved it. convert the date format as per your suggestion and used date.parse method.. Thanks

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used