Deserializing a string from JSON to DateTime in Apex yields "Invalid format" error

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.


If you have datetime in string as: 2017-10-26T12:48:47.000+0000, then you can use below approach. Usually, when we make query in code or dev console or workbench, we get datetime in this format. So, if you want to just copy that value and assign it to date value you can use Datetime.valueOf() by replacing T with space.

String strDate1  = '2017-07-25 00:00:00';
String strDate2 = '2017-07-21 00:00:00';

Datetime dt1 = Datetime.valueOf(strDate1);
Datetime dt2 = Datetime.valueOf(strDate2);

// This is just to show it works fine.
Integer noOfDays = dt2.Date().daysBetween(dt1.Date());
System.debug('No. Of Days : '+noOfDays);