Sh'Jil
Sh'Jil

Reputation: 80

Trying to convert a String to DateTime but it throws exception

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.

Upvotes: 1

Views: 670

Answers (3)

manhtuan21
manhtuan21

Reputation: 3455

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);

Upvotes: 1

Theodore MCA
Theodore MCA

Reputation: 1178

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']),
        );
      },
    );**

Upvotes: 0

Xuuan Thuc
Xuuan Thuc

Reputation: 2521

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"));

Upvotes: 3

Related Questions