5

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

2 Answers 2

14
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.

2
  • 1
    +1 Took the characters right out of my text box. 😄
    – sfdcfox
    Oct 12, 2018 at 17:38
  • For completeness the full code would be Datetime dt = (Datetime)JSON.deserialize('"2018-10-01T00:00:00Z"', Datetime.class);
    – HeXor
    Jan 9 at 9:18
5

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);

You must log in to answer this question.

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