Using java.time
The modern approach is with the java.time classes, supplanting the troublesome old legacy date-time classes.
compute the difference in days between to dates (having a 0 time component)
The LocalDate
class represents a date-only value without time-of-day and without time zone.
The ChronoUnit
enum has some handy methods such as between
.
In defining spans of time, the java.time classes use the Half-Open approach where the beginning is inclusive while the ending is exclusive.
LocalDate start = LocalDate.of( 2017 , Month.JANUARY , 23 );
LocalDate stop = LocalDate.of( 2017 , Month.FEBRUARY , 17 );
long daysBetween = ChronoUnit.DAYS.between( start , stop );
You can represent that span of time as an object, using the Period
class.
Period p = Period.between( start , stop );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.