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

Viewed 51

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":"michael@hotmail.com"
      },
      {
         "id":2,
         "date":"09\/09\/2022",
         "time":"13:10",
         "name":"John",
         "email":"123@hotmail.com"
      }
 ]

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.

1 Answers
 data.sort((a, b) {
    final bFullDate = b.date + b.time;
    final aFullDate = a.date + a.time;
    return bFullDate.compareTo(aFullDate);
  }); 

Edit

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