Remove Edittext date and add five years

Asked

Viewed 94 times

1

I would like to capture a date with a EditText, and from it create another date adding another 5 years. How could I do this?

  • Your text is confused, but I think you want to get the text of a EditText, convert it into a date and add 5 years to it. I got it correctly?

  • Hello friend, that’s exactly it! Thank you!

  • In this case, my answer below should suit you, right?

1 answer

1


Using Date, GregorianCalendar and SimpleDateFormat:

EditText seuEdit = ...;
String texto = seuEdit.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse(texto);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(d);
gc.add(Calendar.YEAR, 5);
String daquiHaCincoAnos = sdf.format(gc.getTime());

Using LocalDate and DateTimeFormatter:

EditText seuEdit = ...;
String texto = seuEdit.getText().toString();
DateTimeFormatter fmt = DateTimeFormatter
    .ofPattern("dd/MM/uuuu")
    .withResolverStyle(ResolverStyle.STRICT);
LocalDate ld1 = LocalDate.parse(texto, fmt);
LocalDate ld2 = ld1.plusYears(5);
String daquiHaCincoAnos = ld2.format(fmt);
  • Hello friend, thank you very much! worked perfectly

  • You can use these tools using only the month and the Year?

  • Simpledateformat sdf = new Simpledateformat("MM/yyyy");

  • @Felipeszulcsewski In this case, you would want to build a date without day, which does not work. You only need the month and the year?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.