How to compare LocalDate instances Java 8

前端 未结 3 508
误落风尘
误落风尘 2020-12-07 22:15

I am writing an app that needs to be quite accurate in dates and I wonder how can I compare LocalDate instances.. for now I was using something like:

LocalDa         


        
3条回答
  •  太阳男子
    2020-12-07 22:44

    Using equals() LocalDate does override equals:

    int compareTo0(LocalDate otherDate) {
        int cmp = (year - otherDate.year);
        if (cmp == 0) {
            cmp = (month - otherDate.month);
            if (cmp == 0) {
                cmp = (day - otherDate.day);
            }
        }
        return cmp;
    }
    

    If you are not happy with the result of equals(), you are good using the predefined methods of LocalDate.

    • isAfter()
    • isBefore()
    • isEqual()

    Notice that all of those method are using the compareTo0() method and just check the cmp value. if you are still getting weird result (which you shouldn't), please attach an example of input and output

提交回复
热议问题