1

While parsing JSON response from webservices, I'm getting date field as '03/21/2012' in a string format. My JSON2Apex parser class is converting this value in String and I'm facing hard time converting this value in Date format.

Illegal assignment from String to Date

    for(accountParser.cls_account caa : classlist){
    Account A = New Account ();
    A.Name = caa.Name;
    A.Start_Date__C = caa.Start_date; // Error: Illegal assignment from String to Date
}

2 Answers 2

2

You can always convert the value again after you have parsed your JSON. Try using the Date.parse(...) method on the string.

A.Start_Date__C = Date.parse(caa.Start_date);
2
  • 1
    The potential downside with this is we don't know how the date is getting generated. This might cause problems for international visitors if the dates switch to DD/MM/YYYY or something else.
    – sfdcfox
    Commented Oct 14, 2016 at 13:53
  • Its an important point to consider, and something I was looking into to add as an edit. The issue with date.parse is that both an international DD/MM/YYYY and MM/DD/YYYY will look valid and be parsed by date.parse, but without any information to tell you which one you have. Without knowing where the date is from, its equally difficult to try to manually parse the date- unless you know that the format will always be the same, in which, it doesn't really matter. Regardless, fixing the json seems the best bet, which I considered out of scope of the question. Commented Oct 14, 2016 at 13:58
1

Technically, what you should do is fix the JSON from the source. Dates in JSON should always be ISO8601 format, to avoid ambiguity between DD/MM/YYYY and MM/DD/YYYY formats. If you can change the data so that your dates are always formatted as YYYY-MM-DD, you can then change Start_Date in your class so that it is a native Date object instead of a simple String. This reduces the odds of parsing errors.

1
  • @battery.cord and sfdcfox .. Thank you both.. I got this working. ... Commented Oct 15, 2016 at 6:23

You must log in to answer this question.

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