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
divya gourigari 14divya gourigari 14 

Datetime.parse() fail in Apex Controller

The failing line is like Datetime.parse('3-31-2022 12:00 AM')
The exception is:
System.TypeException: Invalid date/time: 3-31-2022 12:00 AM
However, if I run this line below in anonymous Apex in dev console, there is no exception.
System.debug('parse'+Datetime.parse('3-31-2022 12:00 AM'));
SwethaSwetha (Salesforce Developers) 
HI Divya,
EDITED:

Can you try
String datetimeParseFormatGMT = Datetime.parse('09/25/2020' + ' ' + '12:15 AM').formatGmt('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
Datetime dtNew = (Datetime) JSON.deserialize('"'+datetimeParseFormatGMT+'"', Datetime.class);

System.debug(dtNew);
See related: https://salesforce.stackexchange.com/questions/320854/how-to-convert-datetime-in-gmt-when-input-format-contains-am-pm
https://salesforce.stackexchange.com/questions/247210/system-typeexception-invalid-date-time-2019-01-03t002601-711-0200

If this information helps, please mark the answer as best. Thank you
divya gourigari 14divya gourigari 14
Hi Swetha,

Thank you for response, i have tried above format but still getting same error.