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:
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;
}