Parsing an ISO 8601 timestamp to a DateTime

I’ve written a simple method to parse a specific kind of ISO 8601 timestamp (GMT, with milliseconds), into a DateTime.

I’m looking to replace it with something that can parse any ISO 8601 timestamp (with or without element separators, missing elements like seconds or milliseconds, with timezone, etc.) Rather that re-inventing the wheel, I’m wondering about using a built-in method.

A similar question about converting ISO 8601 timestamps in Java on Stack Overflow pointed out that, “JAXB must be able to parse ISO8601 date string according to the XML Schema specification”.

I don’t know what JAXB is, or whether it’s available from Apex, but I do know that Apex has all sorts of XML parsers and WSDL tools. The XMLNode class doesn’t have an ISO 8601 parser, but I did find mention of one as part of the JSONParser class (getDatetimeValue() method), and I plan to use that in a wrapper for my conversion.

I’m wondering:

  • If there’s something simpler.
  • If there are known limitations of getDatetimeValue() from JSONParser.

Answer

Rich’s answer was promising, so I tried to figure out why it wouldn’t work, so did a bit of debugging and found that something like this:

System.debug(JSON.deserialize(JSON.serialize(Datetime.now()), Datetime.class));

would print the current Datetime, and that

System.debug(JSON.serialize(Datetime.now());

does in fact serialize to ISo 8601 format, so after a couple of minutes of staring, I realized that the string has to be a valid JSON string, which means, we need double-quotes around it. E.g., try this:

string str = '"2013-01-30T07:38:44.268Z"';
System.debug(JSON.deserialize(str, Datetime.class));

and you should see something like this in the log:

23:40:51.127 (127738280)|USER_DEBUG|[5]|DEBUG|2013-01-30 07:38:44

Attribution
Source : Link , Question Author : tomlogic , Answer Author : Renato Oliveira

Leave a Comment