Add Hours to Java Date and Compare Dates

In this short Java tutorial, I am going to share with you one of the ways you can use to add hours to a Java Date object and then compare that Date object with another date if needed.

Add Hours to Java Date Object

You can use the Instant and Duration objects to add a few hours to a Java Date object. For example:

Instant instant = lockTime.toInstant();
Duration duration = Duration.ofHours( 12 );
Instant hoursLater = instant.plus( duration );

Date laterDate = Date.from( hoursLater );

and now when you have a new Date which contains hours added, you can use the Date.before(), Date.after() or Date.equals() to for Date comparison.

Compare Dates in Java

The below example shows how to use the Date.before() function to compare current Date with the Date objects plus 12 hours.

Instant instant = lockTime.toInstant();
Duration duration = Duration.ofHours( 12 );
Instant hoursLater = instant.plus( duration );

Date laterDate = Date.from( hoursLater );

boolean isDateBefore = laterDate.before( new Date() );

System.out.println("isDateBefore = " + isDateBefore);

I hope this little Java code example was helpful.

Have a look at the below list of Java Video Courses. One of them might take your Java development skills to a whole new level.