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

查看:250
本文介绍了如何比较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

感谢您的帮助..)

推荐答案

http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-\">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.

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

注意所有这些方法都使用 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天全站免登陆