TL; DR
ChronoUnit.DAYS.between( LocalDate.parse( "1999-12-28" ) , LocalDate.parse( "12/31/1999" , DateTimeFormatter.ofPattern( "MM/dd/yyyy" ) ) )
More details
Other answers are out of date. The old date and time classes associated with the earliest versions of Java turned out to be poorly designed, confusing, and complex. Avoid them.
java.time
The Joda-Time project was very successful as a replacement for those old classes. These classes served as inspiration for java.time , which is built into Java 8 and later.
Most of the functionality of java.time is ported to Java 6 and 7 in ThreeTen-Backport and further adapted for Android in ThreeTenABP .
LocalDate
The LocalDate class represents a date value only without time and without a time zone.
Collapsible strings
If your input strings are in the standard ISO 8601 format , the LocalDate class can directly LocalDate string.
LocalDate start = LocalDate.parse( "1999-12-28" );
If not in ISO 8601 format, define a formatting template using DateTimeFormatter .
String input = "12/31/1999"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM/dd/yyyy" ); LocalDate stop = LocalDate.parse( input , formatter );
Elapsed Days Via ChronoUnit
Now get the number of days elapsed between this pair of LocalDate objects. ChronoUnit enum calculates elapsed time.
long totalDays = ChronoUnit.DAYS.between( start , stop ) ;
If you are unfamiliar with Java enumerations, you know that they are much more powerful and useful than regular enumerations in most other programming languages. See Enum doc class, Oracle Tutorial and Wikipedia , to learn more.
About java.time
The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy time classes such as java.util.Date , Calendar and SimpleDateFormat .
The Joda-Time project, now in maintenance mode , we recommend switching to the java.time classes.
To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .
Where to get java.time classes?
- Java SE 8 and SE 9 and later
- Built in.
- Part of the standard Java API with integrated implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) specifically for Android.
- See How to use ThreeTenABP ....
The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter and more .