Note: this answer was written in 2011. I would recommend using java.time now instead of Joda Time.
Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.
I would recommend that you use Joda Time, which is a much better API than Date/Calendar. It sounds like you should use the LocalDate type in this case. You can then use:
int days = Days.daysBetween(date1, date2).getDays();
Answer from Jon Skeet on Stack OverflowNote: this answer was written in 2011. I would recommend using java.time now instead of Joda Time.
Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.
I would recommend that you use Joda Time, which is a much better API than Date/Calendar. It sounds like you should use the LocalDate type in this case. You can then use:
int days = Days.daysBetween(date1, date2).getDays();
Java 8 and later: ChronoUnit.between
Use instances of ChronoUnit to calculate amount of time in different units (days,months, seconds).
For Example:
ChronoUnit.DAYS.between(startDate,endDate)
Videos
UPDATE
The original answer from 2013 is now outdated because some of the classes have been replaced. The new way of doing this is using the new java.time classes.
24-hour days
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
LocalDateTime date1 = LocalDate.parse(inputString1, dtf).atStartOfDay();
LocalDateTime date2 = LocalDate.parse(inputString2, dtf).atStartOfDay();
long daysBetween = Duration.between(date1, date2).toDays();
System.out.println ("Days: " + daysBetween);
} catch (DateTimeParseException e) {
e.printStackTrace();
}
Calendar days
Note that the solution above counts days as generic chunks of 24 hours, not calendar days.
For calendar days, use java.time.temporal.ChronoUnit.DAYS and its between method.
long daysBetween = ChronoUnit.DAYS.between(date1, date2) ;
Original answer (outdated as of Java 8)
You are making some conversions with your Strings that are not necessary. There is a SimpleDateFormat class for it - try this:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
There have been some discussions regarding the correctness of this code. It does indeed take care of leap years. However, the TimeUnit.DAYS.convert function loses precision since milliseconds are converted to days (see the linked doc for more info). If this is a problem, diff can also be converted by hand:
float days = (diff / (1000*60*60*24));
Note that this is a float value, not necessarily an int.
Simplest way:
public static long getDifferenceDays(Date d1, Date d2) {
long diff = d2.getTime() - d1.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}
If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:
LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);
If you want literal 24 hour days, (a duration), you can use the Duration class instead:
LocalDate today = LocalDate.now()
LocalDate yesterday = today.minusDays(1);
// Duration oneDay = Duration.between(today, yesterday); // throws an exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option
For more information, refer to this document: Java SE 8 Date and Time.
Based on VGR's comments here is what you can use:
ChronoUnit.DAYS.between(firstDate, secondDate)
try this:
int epoch = (int) (new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 00:00:00").getTime() / 1000);
you can edit the string in the parse() methods param.
@Michael Borgwardt's answer actually does not work correctly in Android. Rounding errors exist. Example 19th to 21st May says 1 day because it casts 1.99 to 1. Use round before casting to int.
Fix
int diffInDays = (int)Math.round(( (newerDate.getTime() - olderDate.getTime())
/ (1000 * 60 * 60 * 24) ))
Note that this works with UTC dates, so the difference may be a day off if you look at local dates. And getting it to work correctly with local dates requires a completely different approach due to daylight savings time.