Number of days between two dates in Android

anju picture anju · Jan 16, 2015 · Viewed 13.9k times · Source

I need to calculate the number of days between two dates (both dates are also included) entered by a user in EditText. I also need to check weather these days are coming or has already passed. How do I do it?

Answer

Naveen Tamrakar picture Naveen Tamrakar · Jan 16, 2015
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();
}