0

I am facing issue with importing Date field from CSV file. I am giving the date as mm/dd/yyyy in CSV file, and getting error as "Illegal assignment from String to Date".

Below is my code:

public static void Dataload(List<Id> CaseListFromTrigger){  
    string emailMessageId;        
    string str;
    Blob blobbody;              
    List<Sobject> recordstoupload;
    List<String> headervalues = new List<String>();
    string nameFile;
    String[] filelines = new String[]{};
    string AtachParId;
    String csvContent;
    boolean doSentEmail = false;

emailMessageId=[SELECT Id, ParentId FROM EmailMessage where ParentId = :CaseListFromTrigger].Id;
system.debug('***emailMessageId-->'+emailMessageId);

for(Case casedes: [Select Description, Subject from Case where id =: CaseListFromTrigger]){
    str= (casedes.Subject).trim();            
} 

for(Attachment Atch:[SELECT  Id, ParentId,Name,body  FROM Attachment where ParentId = :emailMessageId]){
    blobbody= Atch.Body;
    AtachParId=Atch.ParentId; 
}
system.debug('description--->'+str);                                
System.debug('\n Selected Object--->'+str);

if(str == null)
{
    System.debug('If object is not present');
}
else{
    //Convert the uploaded file which is in BLOB format into a string
     nameFile =blobToString( blobbody,'ISO-8859-1');

    //Now sepatate every row of the excel file
    filelines = nameFile.split('\n');
    Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe();
    Schema.SObjectType objecttypeinfo=gd.get(str);

    //Iterate through every line and create a Account record for each row
    recordstoupload= new List<Sobject>();
    headerValues =new List<String>();
    headerValues = filelines[0].trim().split(',');
    System.debug('**headerValues**'+headerValues );

    for (Integer i=1;i<filelines.size();i++)
    {
        String[] inputvalues = new String[]{};
        inputvalues = filelines[i].split(',');
        System.debug('**inputvalues**'+inputvalues);
        sObject sObj = Schema.getGlobalDescribe().get(str).newSObject() ;
        for(Integer j=0;j<headerValues.size();j++){
            System.debug('**headerValues[j]**'+headerValues[j]+'***inputvalues[j]**'+inputvalues[j]);
            sObj.put(headerValues[j],String.ValueOf(inputvalues[j])) ;                 
        }
        System.debug('**sObj**'+sObj);
        recordstoupload.add(sObj);
    }

    csvContent = headerValues +'\n';
    Database.SaveResult[] srList = Database.insert(recordstoupload, false);
    for (Database.SaveResult sr : srList) {
        if (sr.isSuccess()) {
        System.debug('**SUCCESS**'+sr.getId());
            csvContent = csvContent+'\n';
        }
        else{
            for(Database.Error err : sr.getErrors()) {
                csvContent = csvContent + sr.getErrors()  + '\n';
                System.debug('If object is not present Exception'+sr.getErrors());
            }
        }                
    }       
}       
}



public static String blobToString(Blob input, String inCharset){
    String hex = EncodingUtil.convertToHex(input);
    System.assertEquals(0, hex.length() & 1);
    final Integer bytesCount = hex.length() >> 1;
    String[] bytes = new String[bytesCount];
    for(Integer i = 0; i < bytesCount; ++i)
        bytes[i] =  hex.mid(i << 1, 2);
    return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
}  

Please let me know if i am missing anything.

enter image description here

2
  • You'd need to typecast the date value
    – Raul
    Feb 28, 2017 at 10:59
  • Hi @RahulSharma, Please let me know how i can type cast the date value. If u can help me with code. Feb 28, 2017 at 11:42

1 Answer 1

3

You have to parse the string as a date using Date.valueOf() to make it a date before you can assign it to a date field.

I would use SobjecType.getDescribe().fields.getMap() to get a list of fields, loop over them to find the field currently being worked, check whether or not it's a date field, and then parse accordingly.

UPDATE with example:

I would change this:

for(Integer j=0;j<headerValues.size();j++){
        System.debug('**headerValues[j]**'+headerValues[j]+'***inputvalues[j]**'+inputvalues[j]);
        sObj.put(headerValues[j],String.ValueOf(inputvalues[j])) ;                 
    }

to something like this:

Map<String,Schema.SObjectField> fields = sobj.SObjectType.getDescribe().fields.getMap();
for(Integer j=0;j<headerValues.size();j++){
    Schema.DescribeFieldResult currentField = fields.get(headerValues[j]).getDescribe();
    if(currentField.getType() == Schema.DisplayType.Date){
        sObj.put(headerValues[j],String.ValueOf(Date.parse(inputvalues[j]))) ;
    } else {
        sObj.put(headerValues[j],String.ValueOf(inputvalues[j])) ;
    }                     
}
6
  • Hi @John Towers, I didn't get u. It will be helpful if you can provide the specific line where u want me to add this code. I tried using Date.ValueOf() at line 54 "sObj.put(headerValues[j],Date.ValueOf(inputvalues[j]));". Feb 28, 2017 at 11:41
  • @shashankgupta Right, you can't parse everything as a date. You need to determine which fields on the object are date fields and parse those as dates. The rest should be parsed as strings. I'll update the answer with an example today when I have a chance. Feb 28, 2017 at 12:45
  • Thank you John... Really Appreciated... Till the time i will try to figure out how i can check where i am getting the date field in data. Feb 28, 2017 at 12:59
  • Okay, answer is updated with a sample. You'll probably want to do more checking than that (e.g., make sure the value is in the right format and not null) but this should work as a basic example. Feb 28, 2017 at 13:09
  • Thank you for update in code but i tried using this and it is not parsing my date. Still getting same error. Mar 1, 2017 at 7:52

You must log in to answer this question.

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