0

Given this string value:

String dateTimeString = '20/12/18 16:39:51'; // or '31/10/18 09:35:16'

How would I parse it to a DateTime?

I've tried this:

DateTime dt = DateTime.parse(dateTimeString);

But I get this error:

System.TypeException: Invalid date/time: 20/12/18 16:39:51

I've tried this:

DateTime dt = (DateTime) JSON.deserialize('"' + dateTimeString + '"', DateTime.class);

But I get this error:

System.JSONException: Invalid format: "20/12/18 16:39:51" is malformed at "/12/18 16:39:51"

  • 2
    Where are you getting this string from? Are you not able to at least get four digit years? – Adrian Larson Mar 11 '19 at 13:29
  • @AdrianLarson It's coming from an external API / System – Robs Mar 11 '19 at 13:30
  • 2
    Do you know if you'll get leading zeroes on the time elements? – Adrian Larson Mar 11 '19 at 13:32
  • @AdrianLarson yes the hour will have a leading zero – Robs Mar 11 '19 at 13:36
0

This answer is based on sfdcfox's answer here

Pattern dt = Pattern.compile('(?i)(\\d{2})/(\\d{2})/(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})');
String exampleTime = '20/12/18 16:39:51';
Matcher m = dt.matcher(exampletime);
DateTime result;
if(m.find()) {
    result = DateTime.newInstanceGMT(
        Integer.valueOf('20' + m.group(3)), // yuck
        Integer.valueOf(m.group(2)),
        Integer.valueOf(m.group(1)),
        Integer.valueOf(m.group(4)),
        Integer.valueOf(m.group(5)),
        Integer.valueOf(m.group(6))        
        );
}
System.debug(result);

Note where I pre-pend 20 to the first parameter of the newInstanceGMT method

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.