TL; DR
Instant now = Instant.now(); Boolean isWithinPrior24Hours = ( ! yourJUDate.toInstant().isBefore( now.minus( 24 , ChronoUnit.HOURS) ) ) && ( yourJUDate.toInstant().isBefore( now ) ) ;
More details
Old time-time classes (java.util.Date/.Calendar, java.text.SimpleDateFormat, etc.) turned out to be confusing and erroneous. Avoid them.
For Java 8 and later, use the java.time framework built into Java. For earlier Java, add the Joda-Time framework to your project.
You can easily convert between java.util.Date and any environment.
java.time
The java.time framework, built into Java 8, then supersedes the nasty old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, designed as its successor, similar to the concept, but redesigned. Defined by JSR 310 . Expands ThreeTen-Extra . See Tutorial .
The Instant class represents a moment on the timeline in UTC. If you wanted to request literally 24 hours, not a “day,” then Instant is all we need.
Instant then = yourJUDate.toInstant(); Instant now = Instant.now(); Instant twentyFourHoursEarlier = now.minus( 24 , ChronoUnit.HOURS ); // Is that moment (a) not before 24 hours ago, AND (b) before now (not in the future)? Boolean within24Hours = ( ! then.isBefore( twentyFourHoursEarlier ) ) && then.isBefore( now ) ;
If you meant “day” and not 24 hours, we need to consider the time zone. The day is determined locally in the time zone. Daylight saving time (DST) and other anomalies mean that the day does not always last 24 hours.
Instant then = yourJUDate.toInstant(); ZoneId zoneId = ZoneId.of( "America/Montreal" ); ZonedDateTime now = ZonedDateTime.now( zoneId ); ZonedDateTime oneDayAgo = now.minusDays( 1 ); Boolean within24Hours = ( ! then.isBefore( oneDayAgo ) ) && then.isBefore( now ) ;
Another approach would be to use the Interval class found in the ThreeTen-Extra project. This class represents a pair of Instant objects. The class offers methods such as contains to perform comparisons.
Joda time
The Joda-Time library works the same way as with java.time, which was its source of inspiration.
DateTime dateTime = new DateTime( yourDate );
Or in one line:
boolean isBeforeYesterday = new DateTime( yourDate).isBefore( DateTime.now().minusDays(1) );