2

How do I parse

2018-10-01T00:00:00Z

Into an instance of DateTime

I've tried:

DateTime.valueOfGmt('2018-10-01T00:00:00Z');
DateTime.parse('2018-10-01T00:00:00Z');
DateTime.valueOf('2018-10-01T00:00:00Z');
DateTime.valueOfGmt('2018-10-01T00:00:00Z');

And I always get error:

ERROR: System.TypeException: Invalid date/time: 2018-10-01T00:00:00Z

8
JSON.deserialize('"2018-10-01T00:00:00Z"', DateTime.class);

Note the extra set of double quotes - they allow the JSON parser to interpret that value.

  • 1
    +1 Took the characters right out of my text box. 😄 – sfdcfox Oct 12 '18 at 17:38
3

As an alternative, you can use a regular expression to get the values into a more digestible form:

Pattern dt = Pattern.compile('(?i)(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})Z');
String exampleTime = '2018-10-01T00:00:00z';
Matcher m = dt.matcher(exampletime);
DateTime result;
if(m.find()) {
    result = DateTime.newInstanceGMT(
        Integer.valueOf(m.group(1)),
        Integer.valueOf(m.group(2)),
        Integer.valueOf(m.group(3)),
        Integer.valueOf(m.group(4)),
        Integer.valueOf(m.group(5)),
        Integer.valueOf(m.group(6))        
    );
}
system.debug(result);

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.