-1

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;
}
AKKAweb
  • 3,795
  • 4
  • 33
  • 64
  • 1
    You are doing a small mistake..it should be..```String processDate(data) { return data.date == 'Invalid date' ? DateFormat("mm, dd, yyyy").parse(data.timestamp.toString()) : data.date; }```..you gave `MMM` instead of `mm`..hope it solves your issue..not sure if it works..just give it a try.. – srikanth7785 May 22 '20 at 03:32
  • Thanks for your feedback. I still get an error: FormatException: Trying to read from 20200518100014 at position 15 – AKKAweb May 22 '20 at 03:36
  • https://stackoverflow.com/a/61394854/ – jamesdlin May 22 '20 at 03:50

1 Answers1

2

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);
Lunedor
  • 1,410
  • 1
  • 14
  • 33
  • Based on your answer I was able to create a solution. See question for solution. BTW: MMM is the only thing I could find that formats the month with 3 letters (May, Feb, Jun, etc). Why is that wrong? – AKKAweb May 22 '20 at 03:55
  • MMM isn't wrong actually just MM is more common so if it's by your choice there is no wrong to use it of course. – Lunedor May 22 '20 at 03:58