1

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.

3
  • 1
    an hour ago i gave you a solution with integers, the same works with DateTime objects Commented Jun 7, 2021 at 5:37
  • 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 Commented Jun 7, 2021 at 6:00
  • 1
    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. Commented Jun 7, 2021 at 7:46

2 Answers 2

1
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]);
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Date format needs to be fixed to dd-MM-yyyy
Thanks guys, have tweaked it a little bit and finally got my code.
0
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();

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.