如何比较LocalDate实例Java 8 ?

时间:2021-03-09 22:50:01

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:

我正在编写一个应用程序,它需要在日期上非常准确,我想知道如何比较LocalDate实例。现在我用的是:

LocalDate localdate1 = LocalDate().now();
LocalDate localdate2 = someService.getSomeDate();
localdate1.equals(localdate2);

But I noticed that my app is giving me some confusing results, and I think it is because of the date comparing.

但是我注意到我的应用程序给了我一些令人困惑的结果,我想这是因为比较的日期。

I am thinking about obtaining the time from 1970' in long and compare those two, but I must be easier, I am sure of it

我正在考虑从1970年开始,将这两者进行比较,但我肯定会更容易一些。

1 个解决方案

#1


43  

Using equals() LocalDate does override equals:

使用equals() LocalDate可以覆盖等于:

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.

如果您对equals()的结果不满意,那么您很好地使用了预定义的LocalDate方法。

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

注意,所有这些方法都使用compareTo0()方法,并检查cmp值。如果你仍然有奇怪的结果(你不应该),请附上输入和输出的例子。

#1


43  

Using equals() LocalDate does override equals:

使用equals() LocalDate可以覆盖等于:

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.

如果您对equals()的结果不满意,那么您很好地使用了预定义的LocalDate方法。

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

注意,所有这些方法都使用compareTo0()方法,并检查cmp值。如果你仍然有奇怪的结果(你不应该),请附上输入和输出的例子。