1

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.

2

The answer to the question of whether a single value is valid JSON is probably "it depends on which standard you consider" - see What is the minimum valid JSON?. Apex (at least in the JSON class) considers that it is which is arguably a helpful thing. The documentation even includes an example of a single value.

Internally, the JSON class is probably using a set of type conversion methods to allow it to map string values to specific type fields when a .class argument is supplied. For your example the DateTime converter is getting used.

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.