[SalesForce] Date.ValueOf not accepting null

String str = null;
Date d = Date.valueOf(str);

I am getting the following error when running the above snippet in Anon Apex.

Line: 2, Column: 1
System.NullPointerException: Argument cannot be null.

This is quite strange.

I have a field that contains string data and my target field is of Date Datatype as such I am using Date.ValueOf to convert it.

The quirk here is that the string field may also be null.

My code is failing because Date.ValueOf() does not accept null value as its input parameter.

What I hoped was that upon seeing a null value in the parameter, the Date.ValueOf() will also return a null value.

Can anyone tell me what should I do here ?

What is the null equivalent for a date in Salesforce ?

Best Answer

Why not

Date d = String.isBlank(str)
          ? null
          : Date.valueOf(str);  
Related Topic