SOer SOer - 5 months ago 22
Java Question

java date time compare two

What would be the best way to compare two date in java?

Right now i have array of time like

10.00, 12.00, 2.00, 4.00

How can we find out which time to come up next compared to our computer time?

Let say right now my computer time is 3.15, what should i do to show 4.00 is next?

Date date = new Date();

Answer

The java.util.Date implements the Comparable interface. That means you can very easily compare two date objects with code like this:

if (date1.compareTo(date2) < 0)
{
        System.out.println("date1 is before date2");
}
else if (date1.compareTo(date2) > 0)
{
    System.out.println("date1 is after date2");
}
else
{
    System.out.println("date1 is equal to date2");
}
Comments