RV_Dev RV_Dev - 1 year ago 52
Java Question

Comparing 2 lists of String type containing dates but need to ignore the format

I have 2 lists which contains exact similar dates but the formatting is different. How can I compare those 2 lists are equal ignoring the format of the date?


List 1:

[2016-07-22, 2016-07-20, 2016-07-18, 2016-07-18, 2016-07-18, 2016-07-20, 2016-07-18]

List 2:

[22.07.2016, 20.07.2016, 18.07.2016, 18.07.2016, 18.07.2016, 20.07.2016, 18.07.2016]

Let me know if there is anyway I can do this.

Answer Source


You can use this logic to compare two date.

    SimpleDateFormat sf1= new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sf2= new SimpleDateFormat("dd.MM.yyyy");
    Date date1=sf1.parse("2016-07-18");
    Date date2=sf2.parse("18.07.2016");
    boolean bol=date1.compareTo(date2)==0;
    System.out.println(bol);//true if two dates are equal, false if two date are not equal


    Date[] dl1={sf1.parse("2016-07-22"), sf1.parse("2016-07-20"), sf1.parse("2016-07-18"), sf1.parse("2016-07-18"), sf1.parse("2016-07-18"), sf1.parse("2016-07-20"), sf1.parse("2016-07-18")};
    Date[] dl2={sf2.parse("22.07.2016"), sf2.parse("20.07.2016"), sf2.parse("18.07.2016"), sf2.parse("18.07.2016"), sf2.parse("18.07.2016"), sf2.parse("20.07.2016"), sf2.parse("18.07.2016")};

    List<Date> l1= Arrays.asList(dl1);
    List<Date> l2= Arrays.asList(dl2);

    for(int i=0;i<l1.size();i++){
            System.out.println("Date matched");
            System.out.println("Date did not matched");


Date matched
Date matched
Date matched
Date matched
Date matched
Date matched
Date matched