简体   繁体   中英

How to sort String List by newest in dart

i have String List , per element contains userId+DateTime

    List<String> = [
   '9DWXpF6V4vN8oxqvsHKnOBg2Rz2022-09-14 00:07:52.707',
   '8jk9wQ0U5gNyekzNz84SDb0jDTf12022-09-12 00:07:52.704',
   '0RMRZFCifmSe2CGW6k7Rvq8gvni2022-09-13 00:07:52.704'
    ] 

now i need to sort the list from newest to oldest depends of that DateTime next to User Id

so i am trying the output look like following

  List<String> = [
   '9DWXpF6V4vN8oxqvsHKnOBg2Rz2022-09-14 00:07:52.707',
   '0RMRZFCifmSe2CGW6k7Rvq8gvni2022-09-13 00:07:52.704'
   '8jk9wQ0U5gNyekzNz84SDb0jDTf12022-09-12 00:07:52.704',
        ] 

Note: in my example i did care in day date just to explain my use case but i need to sort my list According to the most recent date and time , not only day date

How can i implement this?

Try this:

RegExp regex = RegExp(r'\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+$');
list.sort(
  (first, second) {
    String? firstDateString = regex.firstMatch(first)?.group(0);
    if (firstDateString == null) {
      throw ArgumentError("$firstDateString does not contain any date");
    }
    String? secondDateString = regex.firstMatch(second)?.group(0);
    if (secondDateString == null) {
      throw ArgumentError("$secondDateString does not contain any date");
    }
    DateTime firstDate = DateTime.parse(firstDateString);
    DateTime secondDate = DateTime.parse(secondDateString);
    return secondDate.compareTo(firstDate);
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM