Wednesday, August 9, 2017

System.TypeException: Invalid date/time Exception in Salesforce Apex

  • When your assigning a value DateTime field using the String then we will end up with this error.
  • If your receiving your date value as part of JSON response and then assiging to DateTime value you will also end up with same error.
To avoid this issue we can use the below two procedures

Sample Error Code:


if(mapName.KeySet().contains('creation_Time') && string.isNotBlank(string.valueof(mapName.get('creation_Time'))))
{

 if(string.valueof(mapName.get('creation_Time')).contains('T'))
  {
    ObjectInsatnce.creation_Time__c = datetime.valueof(string.valueof(mapName.get('cancellation_time')).replace('T',' '));
  }
else
{
 ObjectInsatnce.Cancellation_Time__c = datetime.valueof(mapName.get('cancellation_time'));
}
}

Rectified Source Code:


if(mapName.KeySet().contains('creation_Time') && string.isNotBlank(string.valueof(mapName.get('creation_Time'))))
{

if(string.valueof(mapName.get('creation_Time')).contains('T'))
{
 ObjectInsatnce.creation_Time__c = datetime.valueof(string.valueof(mapName.get('cancellation_time')).replace('T',' '));
}
else
{
  ObjectInsatnce.Cancellation_Time__c = datetime.valueof((String)mapName.get('cancellation_time'));
}
}
 

Hope this helps you....Enjoy!

No comments: