Home > Software design >  How to sort list by date and time if the date and time are two separate strings in Flutter?
How to sort list by date and time if the date and time are two separate strings in Flutter?

Time:09-16

I am using Flutter and I have a list of objects that I get from json api link, for example the json api looks like this:

"data":[
      {
         "id":1,
         "date":"07\/09\/2022",
         "time":"18:30",
         "name":"michael",
         "email":"[email protected]"
      },
      {
         "id":2,
         "date":"09\/09\/2022",
         "time":"13:10",
         "name":"John",
         "email":"[email protected]"
      }
 ]

I want to sort it not just by date but also by time.

I was able to sort it by date but it is not working with date and time at the same time.

Here is the code:

data.sort((a, b) => b.date.compareTo(a.date));

(data is the name of the list)

How can I change this so that it sorts by date and time ?

Thanks.

CodePudding user response:

import 'package:intl/intl.dart';

DateFormat format = DateFormat('dd-MM-yyyy HH:mm');

data.sort((a, b) {
  final bFullDate = format.parse(b.date   ' '   b.time);
  final aFullDate = format.parse(a.date   ' '   a.time);
  return bFullDate.compareTo(aFullDate);
}); 
  • Related