Write a program to sort string date with time in java

Here we used the Collections class to sort the list and wrote a comparator to compare string dates to impose an ordering on a collection of string dates.

Code:
 
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortDates {
 
 public static void main(String[] args) {
  
  List strDts1 =  new ArrayList();
  strDts1.add("25/01/2018 $ 02:17 PM");
  strDts1.add("23/02/2018 $ 03:32 PM");
  strDts1.add("23/02/2018 $ 11:47 AM");
  strDts1.add("25/01/2018 $ 09:34 PM");
  strDts1.add("23/02/2018 $ 07:18 AM");
  strDts1.add("23/02/2018 $ 04:45 AM");
  strDts1.add("25/01/2018 $ 08:29 PM");
  strDts1.add("25/01/2018 $ 07:55 AM");
  
  Collections.sort(strDts1, new Comparator() {
         DateFormat df = new SimpleDateFormat("dd/MM/yyyy '$' hh:mm a");
         @Override
         public int compare(String s1, String s2) {
             try {
                 return df.parse(s1).compareTo(df.parse(s2));
             } catch (ParseException e) {
                 throw new IllegalArgumentException(e);
             }
           }
         });
  
  System.out.println(strDts1);

  
  List strDts2 =  new ArrayList();
  strDts2.add("25/01/2018 # 02:17 PM");
  strDts2.add("23/02/2018 # 03:32 PM");
  strDts2.add("23/02/2018 # 11:47 AM");
  strDts2.add("25/01/2018 # 09:34 PM");
  strDts2.add("23/02/2018 # 07:18 AM");
  strDts2.add("23/02/2018 # 04:45 AM");
  strDts2.add("25/01/2018 # 08:29 PM");
  strDts2.add("25/01/2018 # 07:55 AM");
  
    
  //Java 8
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy '#' hh:mm a");
         Collections.sort(strDts2, (s1, s2) -> LocalDateTime.parse(s1, formatter).
              compareTo(LocalDateTime.parse(s2, formatter)));
     
         System.out.println(strDts2);
 }

}
Output:
[25/01/2018 $ 07:55 AM, 25/01/2018 $ 02:17 PM, 25/01/2018 $ 08:29 PM, 25/01/2018 $ 09:34 PM, 23/02/2018 $ 04:45 AM, 23/02/2018 $ 07:18 AM, 23/02/2018 $ 11:47 AM, 23/02/2018 $ 03:32 PM]
[25/01/2018 # 07:55 AM, 25/01/2018 # 02:17 PM, 25/01/2018 # 08:29 PM, 25/01/2018 # 09:34 PM, 23/02/2018 # 04:45 AM, 23/02/2018 # 07:18 AM, 23/02/2018 # 11:47 AM, 23/02/2018 # 03:32 PM]

No comments: