8

Im trying to format this String into DateTime.

String

2019-01-03T00:26:01.711-02:00

Code

 String data = '2019-01-03T00:26:01.711-02:00';
 Datetime dt = DateTime.parse(data);

Exception

System.TypeException: Invalid date/time: 2019-01-03T00:26:01.711-02:00

2
  • Salesforce datetime format is 'yyyy-MM-dd HH:mm:ss. Are you trying to achieve timezone? Jan 18, 2019 at 19:19
  • Just to add to the confusion a bit, there is at least one place where you would use an ISO 8601 datetime. It's used in SOQL queries like so [SELECT Id FROM Account WHERE CreatedDate > 2019-01-03T00:26:01.711-02:00] (yes, without quotes surrounding the datetime in this case).
    – Derek F
    Jan 18, 2019 at 19:38

2 Answers 2

26

To parse DateTimes in this ISO format, you need to use JSON deserialization.

String data = '2019-01-03T00:26:01.711-02:00';
Datetime dt = (DateTime)JSON.deserialize('"' + data + '"', DateTime.class);

The JSON parser understands ISO format, while DateTime.parse() uses the running user's locale settings.

0
1

String should be in the local time zone and in the format of the user locale.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_datetime.htm#apex_System_Datetime_parse

Example:

Datetime dt = DateTime.parse('10/14/2011 11:46 AM');
String myDtString = dt.format();
system.assertEquals(myDtString, '10/14/2011 11:46 AM');

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .