1

I recently came accross this issue with Datetime deserialization.

When using JSON.deserialize() with a random numeric value, the Datetime instance is created in a strange format, however, for the same numeric value input, Datetime.parse() throws an exception:

Code:

Datetime dt = (Datetime) JSON.deserialize('96598', Datetime.class);
System.debug(dt);
System.debug(Datetime.parse('96598'));

Output:

14:49:35.28 (31544333)|USER_DEBUG|[2]|DEBUG|96598-01-01 00:00:00

Error on line 3, column 1: System.TypeException: Invalid date/time: 96598
AnonymousBlock: line 3, column 1

Also, when trying to insert an SObject with the "deserialized" 96598-01-01 00:00:00 value, I get and DmlException FIELD_INTEGRITY_EXCEPTION.

Any ideas on how to properly validate this instead of having to manually check the input String when deserializing to a Datetime field?

2
  • field integrity exception is because date is out of range for valid year ranges
    – cropredy
    Mar 30, 2021 at 18:16
  • @cropredy Makes sense, the problem is the deserialized Datetime is also out of range, but I get a "valid" Datetime instance. Mar 30, 2021 at 18:23

1 Answer 1

2

Valid SFDC date range for fields in the database is defined in doc to be between Jan 1, 1700 and December 31, 4000

So,

Datetime dt = (Datetime) JSON.deserialize(myString, Datetime.class);
if (dt.year() < 1700 || dt.year() > 4000) {
  throw new MyException('Date is out of range' + dt);
}

If myString is not a valid ISO date format, then the deserialize itself will throw an exception

N.B. SFDC not a great system for Roman Empire applications

4
  • My issue is, since year < 4000, Datetime dt = (Datetime) JSON.deserialize('96598', Datetime.class); should throw me an exception instead of giving me a "valid" Datetime. Because 96598-01-01 00:00:00 is not a valid Datetime Mar 30, 2021 at 18:24
  • your example has a year 96598 which is when we're all part of the synchronicity and are no longer corporeal
    – cropredy
    Mar 30, 2021 at 18:26
  • Exactly. My point is JSON.deserialize should not take this as a valid year, the same way Datetime.parse does not, and therefore throw an exception Mar 30, 2021 at 20:57
  • I guess I'd say, why not? - valid JSON should be accepted without issue and it is up to the application to decide what to do with it; Date dt = Date.newInstance(0001,1,1); also works fine. It would seem like the inconsistency is with Date.parse which is being too restrictive
    – cropredy
    Mar 30, 2021 at 23:45

You must log in to answer this question.

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