Home > Enterprise >  Trying to convert a String to DateTime but it throws exception
Trying to convert a String to DateTime but it throws exception

Time:05-18

I want to display date in format 17 May 2022 but when using DateFormat it is throwing the below Exception.

Trying to read MMMM from 2022-05-16 21:39:39.333741 at position 0

enter image description here

return GroupedListView<dynamic, DateTime>(
  elements: messageList,
  groupBy: (element) => DateFormat.yMMMMd().parse(element['time']),
  groupSeparatorBuilder: (DateTime groupByvalue) {
    return Container(child: Text(DateFormat.yMMMMd().format(groupByvalue)));
  },
  itemBuilder: (context, element) {
    return Container(
      child: Text(element['message']),
    );
  },
);

{ 'time': '2022-05-16 21:39:39.333741', 'message': "hello", 'messagetype': Messagetype.receiver },

above is a sample 'time' i used.

CodePudding user response:

your format date are wrong,

Try convert your date to new format

Example:

dateFormate = DateFormat("yyyy-MM-dd' 'HH:mm:ss.SSSSSS'Z").format(DateTime.parse("2022-05-16 21:39:39.333741"));

CodePudding user response:

return GroupedListView<dynamic, DateTime>(
      elements: messageList,
      groupBy: (element) => DateFormat.yMMMMd().parse(DateTime.parse(element['time'])),
      groupSeparatorBuilder: (DateTime groupByvalue) {
        return Container(child: Text(DateFormat.yMMMMd().format(groupByvalue)));
      },
      itemBuilder: (context, element) {
        return Container(
          child: Text(element['message']),
        );
      },
    );**

CodePudding user response:

You need parse first, then format the type 17 May 2022 later like this :

final dateTime = DateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS'Z").parse('2022-05-16 21:39:39.333741');

final dateTimeString = DateFormat.yMMMMd().format(dateTime);
  • Related