-1
  • I want to calculate age , when user select DOB from date picker
  • Date picker code is same as everywhere

  • My date Format :

    1990/06/07 (getting this format)

  • I need to calculate age i.e current date - DOB 2016-1990 = 26

Code:

public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar calendar = Calendar.getInstance();
            int yy = calendar.get(Calendar.YEAR);
            int mm = calendar.get(Calendar.MONTH);
            int dd = calendar.get(Calendar.DAY_OF_MONTH);

           int a = yy - calendar.get(Calendar.YEAR);
            Log.e("999999", String.valueOf(a));
            return new DatePickerDialog(getActivity(), this, yy, mm, dd);
        }
  • It is giving me 0 . thats the problem
Nadia
  • 33
  • 8
  • 1
    Possible duplicate of [help me in writing an age calculation method in android language:](http://stackoverflow.com/questions/5291503/help-me-in-writing-an-age-calculation-method-in-android-language) – Harshad Pansuriya May 26 '16 at 12:32

1 Answers1

0

You can use JodaTime library for efficient results.

    String dateStr = "04/05/2010";

    SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy");
    Date dateObj = null;
    try {
        dateObj = curFormater.parse(dateStr);
    } catch (ParseException e) {
        e.printStackTrace();
    }


    Period age = calcDiff(dateObj,new Date());
    Toast.makeText(this, PeriodFormat.wordBased().print(age),Toast.LENGTH_SHORT).show();

and Use this method for get difference

  private Period calcDiff(Date startDate,Date endDate)
  {
    DateTime START_DT = (startDate==null)?null:new DateTime(startDate);
    DateTime END_DT = (endDate==null)?null:new DateTime(endDate);

    Period period = new Period(START_DT, END_DT);

    return period;

 }

or as per your requirement you can change PeriodFormat like this

 PeriodFormatter mPeriodFormat;
 mPeriodFormat = new PeriodFormatterBuilder().appendYears().appendSuffix(" year(s) ").appendMonths().appendSuffix(" month(s) ").appendDays().appendSuffix(" day(s) ").printZeroNever().toFormatter();
 Toast.makeText(this,mPeriodFormat.print(age),Toast.LENGTH_SHORT).show();
Abhishek Patel
  • 4,190
  • 1
  • 22
  • 38