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?
Asked
Active
Viewed 1.6k times
2
-
http://stackoverflow.com/questions/20165564/calculating-days-between-two-dates-with-in-java – Naveen Tamrakar Jan 16 '15 at 07:36
-
refer this link:http://stackoverflow.com/questions/23323792/android-days-between-two-dates – prakash Jan 16 '15 at 07:38
2 Answers
15
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();
}

Naveen Tamrakar
- 3,349
- 1
- 19
- 28
2
First get the dates from two edit texts into String
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String firstDate=editText1.getText().toString();
String secondDate=editText2.getText().toString();
After that convert your string to date..
The date difference conversion could be handled in a better way using Java built-in class, TimeUnit. It provides some utility methods to do that:
Date startDate = myFormat.parse(firstDate); // initialize start date
Date endDate = myFormat.parse(secondDate); // initialize end date
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);

King of Masses
- 18,405
- 4
- 60
- 77