Possible Duplicate:
Calculate date/time difference in java
I am a new on Android and I want to make a new app for me. I want to subtruct two dates (dd/mm/yyyy) format by using currentDate. For example I want to find the differences of the days between 01/02/2013 and currentDate. How can I do it?
SimpleDateFormat dfDate = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date d = null;
java.util.Date d1 = null;
Calendar cal = Calendar.getInstance();
try {
d = dfDate.parse("01/02/2012 ");
d1 = dfDate.parse(dfDate.format(cal.getTime()));//Returns 15/10/2012
} catch (java.text.ParseException e) {
e.printStackTrace();
}
int diffInDays = (int) ((d.getTime() - d1.getTime())/ (1000 * 60 * 60 * 24));
System.out.println(diffInDays);
Check Ex1 and Ex2 for more detailed example
You may take a look into DateUtils, that offers some utility methods to compute elapsed time between two dates, but only for representation. Do not use the direct approach to convert between days/milliseconds since it does not take into consideration leap years, leap seconds, summer/winter time changes, etc. Those considerations are handled by Calendar classes.
Update You can use Joda library to perform relative date and time calculations like the one you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With