Home > Back-end >  Sort list by date flutter
Sort list by date flutter

Time:02-02

I need to sort the list by date, but sorting only by first number.

I get this format from JSON 20-JAN-23

and I'm trying to order with model.data.sort((a, b) => b.time!.compareTo(a.time!));

I need to sort the list by date.

I get this format from JSON 20-JAN-23

and I'm trying to order with model.data.sort((a, b) => b.time!.compareTo(a.time!));

but if the year is different, sort only by day. I need to sort by full date.

e.x:

20-SEP-20
02-DEC-21
29-JAN-23
12-JUN-20

My sorting is :

02-DEC-21
12-JUN-20
20-SEP-20
29-JAN-23

but I want to be:

12-JUN-20
20-SEP-20
02-DEC-21
29-JAN-23

CodePudding user response:

import 'package:intl/intl.dart';

int sortDates(String a, String b) {
  String formatDate(String s) => s.replaceRange(4, 6, s.substring(4, 6).toLowerCase());
  DateTime parse(String s) => DateFormat("dd-MMM-yy").parse(formatDate(s));
  return parse(a).compareTo(parse(b));
}

...
model.data.sort(sortDates);
...

CodePudding user response:

Use this:

...
int sorterFunction(String a, String b) {
    String formatText(String dateAsString) {
      final date = dateAsString.substring(0,2);
      final month = formatMonth(dateAsString.substring(3,6));
      final year = '20${dateAsString.substring(7)}';
      return '$date-$month-$year';
    }
    String formatMonth(String text) {
      switch (text) {
        case 'JAN': return 'Jan';
        case 'FEB': return 'Feb';
        case 'MAR': return 'Mar';
        case 'APR': return 'Apr';
        case 'MAY': return 'May';
        case 'JUN': return 'Jun';
        case 'JUL': return 'Jul';
        case 'AUG': return 'Aug';
        case 'SEP': return 'Sep';
        case 'OCT': return 'Oct';
        case 'NOV': return 'Nov';
        case 'DEC': return 'Dec';
        default: return 'Jan';
        }
    }

    final dateA = DateFormat('dd-MMM-yy').parse(formatText(a));
    final dateB = DateFormat('dd-MMM-yy').parse(formatText(b));
    return dateA.compareTo(dateB);
}
...
...
model.data.sort(sorterFunction);
...
  • Related