简体   繁体   中英

Best Approach to compare two dates in java

what is the best approach to compare two dates in java?

i need to set date, month and year for both the dates and i should compare those both dates

I am using Calendar object to set the values

Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.YEAR, 2015);
calendar1.set(Calendar.MONTH, 5);
calendar1.set(Calendar.DATE, 17);

Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.YEAR, 2015);
calendar2.set(Calendar.MONTH, 5);
calendar2.set(Calendar.DATE, 18);

    if (calendar1.compareTo(calendar2) < 0) {
        // if calendar1 is less than calendar2
    } 

I handling lot of comparisons throughout my application.

For Performance, Using java.util.Calendar is the right approach?

It's probably better to use Java 8's LocalDate, since Calendar also represents time. In your example, calendar1 and calendar2 would have slightly different times, since you let them default.

If you are using an earlier version of Java, you can use the Joda date library instead.

Finally, if you don't have an actual performance problem, don't worry about it. If you do have a performance problem that you know is attributable to date comparisons (because you profiled the code), try different ways of doing the comparison, and benchmark them to find out what is most performant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM