How to sort a List<String> of formatted dates in dart?

106

Solution 1

import 'package:intl/intl.dart';

List<String> getSortedDates(List<String> dates){

  //Formatting for acceptable DateTime format
  DateFormat formatter = DateFormat("dd-MM-yyyy");

  //Mapping to convert into appropriate dateFormat
  List<DateTime> _formattedDates = dates.map(formatter.parse).toList();
  
  //Apply sort function on formatted dates
  _formattedDates.sort();

  //Mapping through sorted dates to return a List<String> with same formatting as passed List's elements
  return _formattedDates.map(formatter.format).toList();

}

Solution 2

import 'package:intl/intl.dart';


 List dates = ["24-06-2021",
                  "27-05-2021",
                  "21-04-2021",
                  "29-07-2021",
                  "15-12-2021"];

  List<DateTime> newdates = [];
  DateFormat format = DateFormat("dd-MM-yyyy");

  for (int i = 0; i < dates.length; i++) {
    newdates.add(format.parse(dates[i]));
  }
  newdates.sort((a,b) => a.compareTo(b));

  for (int i = 0; i < dates.length; i++) {
    print(newdates[i]);
  }
Share:
106
Vinay Saurabh
Author by

Vinay Saurabh

Updated on December 30, 2022

Comments

  • Vinay Saurabh
    Vinay Saurabh over 1 year

    I have tried this on dartpad,

    void main() {
      final List<String> dates=["24-06-2021","27-05-2021","21-04-2021","29-07-2021","15-12-2021"];
      var sorted = dates..sort((a,b) => a.compareTo(b));
      print(sorted);
    }
    

    Output : [15-12-2021, 21-04-2021, 24-06-2021, 27-05-2021, 29-07-2021]
    Desired : [21-04-2021, 27-05-2021, 24-06-2021, 29-07-2021, 15-12-2021]

    Any help is appreciated.

    • pskink
      pskink almost 3 years
      an hour ago i gave you a solution with integers, the same works with DateTime objects
    • Vinay Saurabh
      Vinay Saurabh almost 3 years
      This code works, ` void main() { final List<String> dates=["2021-06-24","2021-05-24"]; var sorted = dates.map(DateTime.parse).toList()..sort((a,b) => a.compareTo(b)); for(int i =0;i<sorted.length;i++){ String date = '${sorted[i].day}-${sorted[i].month}-${sorted[i].year}'; print(date); } } ` but is it efficient. @pskink
    • jamesdlin
      jamesdlin almost 3 years
      That's as efficient as you can get. You can't do a comparison-based sort faster than O(n log n), and converting everything to DateTime objects first means that you don't need to reparse the same strings when performing multiple comparisons of the same element.
  • Alex Radzishevsky
    Alex Radzishevsky almost 3 years
    Date format needs to be fixed to dd-MM-yyyy
  • Vinay Saurabh
    Vinay Saurabh almost 3 years
    Thanks guys, have tweaked it a little bit and finally got my code.