如何比较 LocalDate 实例 Java 8 [英] How to compare LocalDate instances Java 8

查看:44
本文介绍了如何比较 LocalDate 实例 Java 8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个需要非常准确的日期的应用程序,我想知道如何比较 LocalDate 实例.现在我正在使用类似的东西:

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 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.

我正在考虑获取 1970 年以来的时间并比较这两个,但我必须更容易,我很确定

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

推荐答案

使用 equals()LocalDate 确实覆盖等于:

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;
}

如果您对 equals() 的结果不满意,最好使用 LocalDate 的预定义方法.

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

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

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

这篇关于如何比较 LocalDate 实例 Java 8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆