This question is based on what I encountered on another question which goes like this: How do I convert text to datetime?
In our legacy system feed we are getting the following text value. "2016-11-17T10:04:31.000+08:00" I would like to know whether it is possible to convert this text value to a datetime data type. 2016-11-17T18:04:31.000Z
Normally, I would solve it like this:
String oldD = '2016-11-17T10:04:31.000+08:00';
Datetime newD = Datetime.newInstance(
Integer.valueOf(oldD.subString(0,4)),
Integer.valueOf(oldD.subString(5,7)),
Integer.valueOf(oldD.subString(8,10)),
Integer.valueOf(oldD.subString(11,13)),
Integer.valueOf(oldD.subString(14,16)),
Integer.valueOf(oldD.subString(17,19))
); //this will be constructed in user timezone
system.debug('newD = '+ newD);
However, one fine gentleman solved it with one line of code! and it was:
DateTime t = (DateTime)json.deserialize('"2016-11-17T10:04:31.000+08:00"', datetime.class);
Of course, this one line rocks!!
Q1. Can anyone explain me how and why this actually worked? The string is not even a JSON string!
Q2. Is this mentioned in the salesforce dev docs?
Q3. If no, then how can I learn such awesome "tricks"?
Thanks in advance.