sort array list of special strings, by date

前端 未结 6 653
有刺的猬
有刺的猬 2021-01-25 10:33

I have an arrayList.

This is an arrayList of strings. The string contains a \"Date.toString\" in format of \"January 1, 1970, 00:00:00 GMT\" +

6条回答
  •  庸人自扰
    2021-01-25 10:52

    Convert the array into a list of dates and then sort them:

    List dates = new ArrayList();
    for(String s : dateStringArray){
      // split the date and task name
      Pattern p = Pattern.compile("(\\w+ \\d{1,2}, \\d{4}, \\d{2}:\\d{2}:\\d{2} \\w{3})(.*)");
      Matcher matcher = p.matcher(s);
      String taskname = "";
      String datestring = "";
      if (matcher.find()) {
        datestring = matcher.group(1);
        taskname = matcher.group(2);
      }
      // parse the date
      Date d = new SimpleDateFormat("MMMM dd, yyyy, HH:mm:ss z", 
                   Locale.ENGLISH).parse(datestring);
      dates.add(d);
    }
    // sort the dates
    Collections.sort(dates);
    

    If you want to keep the task names, you will have to make own objects that have the date and the task as fields and are comparable by the dates.

提交回复
热议问题