Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find difference two dates on android app [duplicate]

Tags:

date

android

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?

like image 786
Çağatay Aktaş Avatar asked Oct 15 '12 09:10

Çağatay Aktaş


2 Answers

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

like image 63
Ram kiran Pachigolla Avatar answered Oct 16 '22 15:10

Ram kiran Pachigolla


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.

like image 32
Fernando Miguélez Avatar answered Oct 16 '22 15:10

Fernando Miguélez