Calculate age using EditText and not using Calendar

4

How can I calculate the age (including day and month) using an EditText? Right now I do it using a Calendar, but I would like to write the date 23/01/2017 (Example) in the EditText to calculate the age.

EditText that I want to use to calculate age:

  

editText1 = (EditText) findViewById (R.id.editText1);

MainActivity:

public class MainActivity extends Activity implements OnClickListener{
    private Button btnStart;
    static final int DATE_START_DIALOG_ID = 0;
    private int startYear=1970;
    private int startMonth=6;
    private int startDay=15;
    private AgeCalculation age = null;
    private TextView currentDate;
    private TextView birthDate;
    private TextView result;

    EditText editText1;
    TextView edad;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        age=new AgeCalculation();
        currentDate=(TextView) findViewById(R.id.textView1);
        currentDate.setText("Current Date(DD/MM/YY) : "+age.getCurrentDate());
        birthDate=(TextView) findViewById(R.id.textView2);
        result=(TextView) findViewById(R.id.textView3);
        edad=(TextView) findViewById(R.id.edad);
        editText1=(EditText) findViewById(R.id.editText1);
        btnStart=(Button) findViewById(R.id.button1);
        btnStart.setOnClickListener(this);

    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_START_DIALOG_ID:
                return new DatePickerDialog(this,
                        mDateSetListener,
                        startYear, startMonth, startDay);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener mDateSetListener
            = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {
            startYear=selectedYear;
            startMonth=selectedMonth;
            startDay=selectedDay;
            age.setDateOfBirth(startYear, startMonth, startDay);
            birthDate.setText("Date of Birth(DD/MM/YY): "+selectedDay+":"+(startMonth+1)+":"+startYear);
            calculateAge();
        }
    };
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                showDialog(DATE_START_DIALOG_ID);
                break;

            default:
                break;
        }
    }
    private void calculateAge()
    {
        age.calcualteYear();
        age.calcualteMonth();
        age.calcualteDay();
        Toast.makeText(getBaseContext(), "click the resulted button"+age.getResult() , Toast.LENGTH_SHORT).show();
        result.setText(age.getResult()+(" Años"));

        String[] dayMonthYear = age.getResult().split(":");
        String year = dayMonthYear[2];
        edad.setText(year  + " Años");
    }
}

AgeCalculation:

public class AgeCalculation {
    private int startYear;
    private int startMonth;
    private int startDay;
    private int endYear;
    private int endMonth;
    private int endDay;
    private int resYear;
    private int resMonth;
    private int resDay;
    private Calendar end;
    public String getCurrentDate()
    {
        end=Calendar.getInstance();
        endYear=end.get(Calendar.YEAR);
        endMonth=end.get(Calendar.MONTH);
        endMonth++;
        endDay=end.get(Calendar.DAY_OF_MONTH);
        return endDay+":"+endMonth+":"+endYear;
    }
    public void setDateOfBirth(int sYear, int sMonth, int sDay)
    {
        startYear=sYear;
        startMonth=sMonth;
        startMonth++;
        startDay=sDay;

    }
    public void calcualteYear()
    {
        resYear=endYear-startYear;

    }

    public void calcualteMonth()
    {
        if(endMonth>=startMonth)
        {
            resMonth= endMonth-startMonth;
        }
        else
        {
            resMonth=endMonth-startMonth;
            resMonth=12+resMonth;
            resYear--;
        }

    }
    public void  calcualteDay()
    {

        if(endDay>=startDay)
        {
            resDay= endDay-startDay;
        }
        else
        {
            resDay=endDay-startDay;
            resDay=30+resDay;
            if(resMonth==0)
            {
                resMonth=11;
                resYear--;
            }
            else
            {
                resMonth--;
            }

        }
    }

    public String getResult()
    {
        return resDay+":"+resMonth+":"+resYear;
    }

}
    
asked by UserNameYo 23.01.2017 в 16:38
source

2 answers

4

You can extend the EditText and create a DateEditText , which uses a InputFilter to format and check the data while the user enters it.

public class DateEditText extends EditText{...}

necessary changes:

public DateEditText(Context context) {
    super(context);
    setupFilter();
}

private void setupFilter(){
    InputFilter[] filters = new InputFilter[1];

    filters[0] = new InputFilter() {

        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (end > start) {
                String destTxt = dest.toString();
                String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend);

                Log.d("InputFilter",resultingTxt);

                if (!resultingTxt.matches("^(\d{0,2}|\d{2}/{1}\d{0,2}|\d{2}/{1}\d{2}/{1}\d{0,4})$")) {

                    if (source instanceof Spanned) {
                        SpannableString sp = new SpannableString("");
                        return sp;
                    } else {
                        return "";
                    }

                }

            }

            return null;
        }

    };
    this.getEditText().setFilters(filters);
}

Keep in mind when you develop your regex that you have to allow not only the final data entry format, but also all partial income, such as:

1
12
12/0
12/05
12/05/
12/05/1
12/05/16

After receiving the EditText text, you can convert your data using SimpleDateFormat :

SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
Date fecha = formato.parse(editText1.getText().toString());

That's code that I used for another type of EditText specialized, if you have problems with the regex, leave me a comment and I'll help you.

added and corrected

La regex:

matches("^(\d{0,2}|\d{2}/{1}\d{0,2}|\d{2}/{1}\d{2}/{1}\d{0,4})$");

should help you while, even if it does not check if the data is valid in itself, it only guarantees that it works with the format.

Just in case, I recommend android:inputType="phone" in the layout, because "number" does not give you the key for "/".

    
answered by 23.01.2017 / 17:06
source
1

The process that has occurred to me is:

You create an object Date in the parse of the string of editText1.

Date objFecha;

try{

    String fechaS=(editText1.getText().toString());
    objFecha= formatter.parse(fechaS);

}catch (ParseException e) {
    e.printStackTrace();
}

A LocaleDate is created with the date and compared with today's

//pongo Month + 1 porque empieza a contar en 0

LocalDate cumpleaños = new LocalDate (objFecha.getYear(),objFecha.getMonth() +1,objFecha.getDate() );

LocalDate hoy = new LocalDate();

Years edad= Years.yearsBetween(cumpleaños, hoy);
    
answered by 23.01.2017 в 17:01