how can I sort list items in flutter/dart based on dateTIme and TimeOfDay?

251

use this:

YOURLIST.sort((a, b)=> a.microsecondsSinceEpoch.compareTo(b.microsecondsSinceEpoch));

you can parse DateTime from date and time that users select as follow:

DateTime testDate = DateTime.parse("2021-08-01 20:18:04");
print(testDate.millisecondsSinceEpoch);

so you can replace 2021-08-01 20:18:04 with selectedDate selectedTime

Share:
251
MhdBasilE
Author by

MhdBasilE

Updated on December 31, 2022

Comments

  • MhdBasilE
    MhdBasilE over 1 year

    I'm making a Todo app, so I want to sort list of tasks based on date and time chosen by user, currently I'm soring like this, but its not accurate all the time, any other suggestions??

    class TaskModel { //model of task
    final String? id;
    final String? title;
    final DateTime? date;
    final String? field;
    final TimeOfDay? time;
    bool isFinished;
    TaskModel({
    @required this.date,
    @required this.id,
    @required this.title,
    @required this.time,
    this.field = 'other',
    this.isFinished = false,
    });
    //method right now I'm using to compare(not efficient)
    _tasks.sort((a, b) => a.date!.compareTo(b.date!));
    _tasks.sort((a, b) => a.time!.hour.compareTo(b.time!.hour));
    _tasks.sort((a, b) => a.time!.minute.compareTo(b.time!.minute));
    
    • Abbasihsn
      Abbasihsn almost 3 years
      you can use timestamps, MillisecondsSinceEpoch, or MicrosecondsSinceEpoch. first convert the date to one of them and then you can compare them efficiently. other solution can be using custom compare
    • MhdBasilE
      MhdBasilE almost 3 years
      i have to objects 1)Date chosen by user from date picker 2)time chosen by user from a time picker...so i have to consider both of them while soring ...is this way can do that?
    • Abbasihsn
      Abbasihsn almost 3 years
      see my answer, I have updated it.