-2

hello i am creating an android app in which i have two string of different dates now i want to get number of years between these dates anyone please help me how i can do this? here is my code

                    String  birthday=p.getString("BirthDay");

                     Log.i("bd", String.valueOf(birthday));
                     Calendar c = Calendar.getInstance();


                     SimpleDateFormat df = new SimpleDateFormat("dd MMM, yyyy");
                     final String formattedDate = df.format(c.getTime());
                     Log.i("formattedDate", String.valueOf(formattedDate));

where birthday is saved date and formatteddate is current date now i want difference between these

John
  • 15
  • 1
  • 6
  • Parse the strings to dates, subtract them, then get the years from the result. All date/times in Android are longs based on the Unix epoch. – Simon Nov 27 '14 at 11:24
  • you can get the year from the calendar with `c.get(Calendar.YEAR)`. – Blackbelt Nov 27 '14 at 11:26

3 Answers3

1

Please try this code

    String birthday = p.getString("BirthDay");
    Calendar calendarBirthday = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy");
    calendarBirthday.setTime(sdf.parse(birthday));
    Calendar calendarNow = Calendar.getInstance();
    int yearNow = calendarNow.get(Calendar.YEAR);
    int yearBirthday = calendarBirthday.get(Calendar.YEAR);
    int years = yearNow - yearBirthday;
-1
int getYear(Date date1,Date date2){ 
  SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy");
  Integer.parseInt(simpleDateformat.format(date1));

  return Integer.parseInt(simpleDateformat.format(date2))- Integer.parseInt(simpleDateformat.format(date1));

}
Miki Franko
  • 687
  • 3
  • 7
-1

pass your date of birth

public int getAge (int _year, int _month, int _day) {

    GregorianCalendar cal = new GregorianCalendar();
    int y, m, d, a;         

    y = cal.get(Calendar.YEAR);
    m = cal.get(Calendar.MONTH) + 1;
    d = cal.get(Calendar.DAY_OF_MONTH);
    cal.set(_year, _month, _day);
    a = y - cal.get(Calendar.YEAR);
    if ((m < cal.get(Calendar.MONTH))
                    || ((m == cal.get(Calendar.MONTH)) && (d < cal
                                    .get(Calendar.DAY_OF_MONTH)))) {
            --a;
    }
    if(a < 0)
            throw new IllegalArgumentException("Age < 0");
    return a;
}
deepak825
  • 432
  • 2
  • 8