Java date time compare two

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

Now I have an array of time, for example

10.00, 12.00, 2.00, 4.00

How can we find out what time to think up compared to our computer time?

Let's say now my computer time is 3.15, what should I do to show that 4.00 is next?

Date date = new Date();
+3
source share
4 answers

java.util.Date implements the Comparable interface. This means that you can easily compare two date objects with this code:

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");
}
+12
source

Joda Time. LocalTime new LocalTime(), ... compareTo, isBefore isAfter.

Joda Time Date/Calendar .

+5

JodaTime, , , ( ), Joda, :

public static String getNextHour() {
    Calendar c = new GregorianCalendar();
    int minsLeft = 60 - c.get(Calendar.MINUTE);
    c.add(Calendar.MINUTE, minsLeft);

    SimpleDateFormat sdf = new SimpleDateFormat("h:mm");
    return sdf.format(c.getTime());
}
0

java.util.Date . , . , Java, , . java.sql.Time , , .

java.time

java.time Java 8 . . Oracle. rel= no nofollow. > Joda-Time. java.time back-ported Jave 6 7 Android. ; .

LocalTime .

, List, .

List<LocalTime> times = new ArrayList<>( 4 );
times.add( LocalTime.of( 10 , 0 );
times.add( LocalTime.of( 12 , 0 );
times.add( LocalTime.of( 14 , 0 );
times.add( LocalTime.of( 16 , 0 );

.

LocalTime sample = LocalTime.of( 15 , 15 ); // Quarter-hour past 3 in the afternoon.

Or get the current time of day. Specify the time zone as it is more reliable than implicit, depending on your default JVM current time zone .

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalTime sample = LocalTime.now( zoneId );

Scroll Listto find the first item that will be later in the day than your sample time. For comparison, use isAfter, isBeforeor equals.

LocalTime hit = null;
for ( LocalTime time : times ) {
    if ( time.isAfter( sample ) ) {
        hit = time;
        break; // Bail-out of this FOR loop.
    }
}
// Test if 'hit' is still null, meaning no appropriate value found.
if ( null == hit ) { … } else ( … }
0
source

Source: https://habr.com/ru/post/1777296/


All Articles