How to Sort List by Date in Dart/Flutter

Posted by

How to Sort List of Date String in Ascending Order:

void main() {
List<String> datestrings = [ 
  "2022-02-12", 
  "2022-01-23",
  "2022-12-11",
  "2022-01-14",
];

datestrings.sort((a, b){ //sorting in ascending order
    return DateTime.parse(a).compareTo(DateTime.parse(b));
});

print(datestrings);
}

OutPut:

output: [2010-01-23, 2013-01-14, 2020-02-12, 2021-12-11]

How to Sort List of Date String in Descending Order:

void main() {
List<String> datestrings = [ 
  "2022-02-12", 
  "2022-01-23",
  "2022-12-11",
  "2022-01-14",
];

datestrings.sort((a, b){ //sorting in descending order
    return DateTime.parse(b).compareTo(DateTime.parse(a));
});

print(datestrings);
 
}

OutPut:

[2022-12-11, 2022-02-12, 2022-01-23, 2022-01-14]
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x