Error Handling: System.TypeException: Invalid date/time
Error Message
System.TypeException: Invalid date/time
Why Are We Seeing This Error Message?
The error message System.TypeException: Invalid date/time may appear when attempting to execute a query in Apex with an invalid datetime format. For example, if you allow the user to input a date as a parameter for an LWC query.
The following query will run correctly in Apex:
SELECT Id FROM Contact WHERE CreatedDate > 2022-01-01T09:00:00+03:00
However, if we try to execute it with a date variable of String type as follows, we will receive an error message:
String myDateTime = '2022-01-01T09:00:00+03:00';
List myContacts = [SELECT Id FROM Contact WHERE CreatedDate > :dt];
Line: 3, Column: 28 Invalid bind expression type of String for column of type Datetime
One way to try to solve the problem is to attempt to convert from String to Datetime as follows:
String myDateTime = '2022-01-01T09:00:00+03:00';
Datetime myParsedDatetime = Datetime.parse(myDateTime);
List myContacts = [SELECT Id FROM Contact WHERE CreatedDate > :myParsedDatetime];
However, this attempt will fail, and the error message we will receive is the one we started with:
Line: 2, Column: 1 System.TypeException: Invalid date/time: 2022-01-01T09:00:00+03:00
Solution
To solve the conversion problem from String to Datetime without receiving a parsing error, we want to use the deserialize method of the JSON class to cast our string to Datetime as follows:
String myDateTime = '2022-01-01T09:00:00+03:00';
Datetime dt = (DateTime)JSON.deserialize('"' + myDateTime + '"', DateTime.class);
List myContacts = [SELECT Id FROM Contact WHERE CreatedDate > :dt];
Now we can successfully run our code with the original date as a string.