In my app, there are some situations where the date field in the JSON is invalid. Instead of displaying "Invalid date" I would like to display another field called timestamp. This field, however, is at this format: 20200518100014. I would like to convert that to May 18, 2020.

I have not been successful and this is the latest code I have

String processDate(data) {
    var timeStamp = DateFormat("MMM dd, yyyy").parse(data.timestamp.toString());
    return data.date == 'Invalid date' ? timeStamp : data.date;
}

This causes the following error:

enter image description here

How can I fix this issue to display the date as May 18, 2020 format instead.


ANSWER:

Based on @Lunedor answer below, I was able to create the following solution:

String processDate(data) {
    String date = data.timestamp.toString();
    String dateWithT = date.substring(0, 8) + 'T' + date.substring(8);
    String dateTime = DateFormat("MMM dd, yyyy").format(DateTime.parse(dateWithT));

    return data.date == 'Invalid date' ? dateTime : data.date;
}


Solution 1: Lunedor

I am skipping MMM mistake, check this answer to see what type of strings can be parse as time and date:

https://stackoverflow.com/a/60988096/12880676

And your case you can use the method in this answer. I am just copy and paste the code:

String date = '20180626170555';
String dateWithT = date.substring(0, 8) + 'T' + date.substring(8);
DateTime dateTime = DateTime.parse(dateWithT);