-3

I want to calculate age from D.O.B. I am getting date of birth from below code. Now i want to calculate user age and I want to show age in another textView. How can I achieve this ?

dateFormatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);

public void setDateTimeField() {
        date();

        Calendar newCalendar = Calendar.getInstance();
        fromDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                txtDatePicker.setText(dateFormatter.format(newDate.getTime()));
            }

        },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));

    }

    public void date(){

        txtDatePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fromDatePickerDialog.show();
            }
        });
    }
Noreen Khan
  • 223
  • 1
  • 12

1 Answers1

1

Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API).

Java 8 has something very similar and is worth checking out.

e.g.

LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);

which is as simple as you could want.

Great examples for using dates with Java 8: Java 8 Date Examples

Happy Coding!

Shrenik Shah
  • 1,490
  • 9
  • 19
  • Android studio giving error - Cannot resolve symbol 'LocalDate'. – Noreen Khan Sep 26 '16 at 06:22
  • have you added joda lib ? – Shrenik Shah Sep 26 '16 at 06:22
  • ya Now its working fine but how to set dynamically date in LocalDate birthdate = new LocalDate (1970, 1, 20); I am getting this error - java.lang.IllegalArgumentException: yyyy,dd,mm – Noreen Khan Sep 26 '16 at 07:33
  • 1
    separate dynamic date into year month and day using calender object, after that pass it to LocalDate respectively. – Shrenik Shah Sep 26 '16 at 07:36
  • Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); LocalDate birthdate = new LocalDate (newDate.getTime()); LocalDate now = new LocalDate(); Years age = Years.yearsBetween(birthdate, now); txtAge.setText(String.valueOf(age.getYears())); – Noreen Khan Sep 26 '16 at 07:44