简体   繁体   中英

How to sort a list of time strings in Java or Groovy

I have a list of strings, each one contains time like this:

"03:00 AM", "12:30 PM", "16:15"

I need to sort them in order: put "am" times first and compare hours, not just first digits in a string.

This works for groovy, with all cases you gave:

List dates = [ "16:15", "12:30 PM", "07:00", "03:00 AM" ]

dates.sort { d ->
  [ 'h:mm a', 'H:mm' ].findResult { fmt ->
    try {
      Date.parse( fmt, d ).time
    } catch( e ) {}
  }
}

It basically tries with AM/PM and then tries without it if that fails

All of Java's sorting machinery -- for example, the Collections.sort() methods -- work with (or can work with) a comparator -- an instance of a class you write yourself that implements java.util.Comparator . That interface has a compare() method, and you can implement it to do any kind of comparison you want. That's what you'll need to do here.

Use the SimpleDateFormat class to determine the time which represents each string and then compare that numeric value when sorting. It looks like the time strings you're dealing with can have different kinds of formats, so I've edited the answer to support strings of format 03:00AM or 16:23

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class TimeStringComparator implements Comparator<String>{
   private DateFormat primaryFormat = new SimpleDateFormat("h:mm a");
   private DateFormat secondaryFormat = new SimpleDateFormat("H:mm");

   @Override
   public int compare(String time1, String time2){
       return timeInMillis(time1) - timeInMillis(time2);
   }

   public int timeInMillis(String time){
       return timeInMillis(time, primaryFormat);
   }

   private int timeInMillis(String time, DateFormat format) {
        // you may need more advanced logic here when parsing the time if some times have am/pm and others don't.
       try{
            Date date = format.parse(time);
            return (int)date.getTime();
       }catch(ParseException e){
           if(format != secondaryFormat){
               return timeInMillis(time, secondaryFormat);
           }else{
               throw e;
           }
       }
    }

   public static void main(String[] args){
       List<String> times = Arrays.asList(new String[]{"03:00 AM", "12:30 PM", "16:15"});
       Collections.sort(times, new TimeStringComparator());
       System.out.println(times);
   }

}

As @Ernest said, you need to use a Comparator. You can do something like this with your list:

List<String> times;
Collections.sort(times, new Comparator<String>() { 
     @Override 
     public int compare(String time1, String time2) { 

        // Sorting implementation here
     } 
 });

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