Add days to a date in Edittext

Asked

Viewed 720 times

1

I have a date in the dd-MM-yyyy format in an Edittext with Inputtype="date" called "start".

I want to take this date, put your content in the Date variable called "inifer" and on this date add an entire variable called "diafer" and subtract 1 and play in the variable "terfer".

My commands are:

    String datastr = inicio.getText().toString();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Date inifer = new Date();
    try
    {
        inifer = dateFormat.parse(datastr);
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }

    Log.i("Data de início", dateFormat.format(inifer));
    int diafer = Integer.parseInt(diasfer.getText().toString());
    Log.i("dias de férias", String.valueOf(diafer));

    Calendar c = Calendar.getInstance();
    Date terfer = inifer;
    c.setTime(terfer);
    c.add(c.DATE, diafer - 1);
    terfer.setTime(c.DATE);
    int mester = c.MONTH;
    int diater = c.DAY_OF_MONTH;
    Log.i("mês de término férias", String.valueOf(mester));
    Log.i("dia de término férias", String.valueOf(diater));

Logs show the correct content, except the last two.

With the date of 05/10/2016 and 30 days of vacation, they show the month 2 and the day 5, when it should be month 6 and day 8, because 29 days after 05/10/2016 is day 06/08/2016.

Where did I go wrong?

  • Shows end date 31/12/1969. I switched to the code and gave the same result: `code Calendar c = Calendar.getInstance(); Date terfer = inifer; c.set(c.DAY_OF_MONTH, dia); c.set(c.MONTH, mes); c.set(c.YEAR); c.add(c.DAY_OF_MONTH, diafer - 1); terfer.setTime(c.DATE); int Mester = c.MONTH; int diater = c.DAY_OF_MONTH; Log. i("End date", dateFormat.format(terfer)); Log. i("end month vacation", String.valueOf(Mester)); Log. i("vacation end day", String.valueOf(diater));

1 answer

1

Use the method get of Calendar to return the information of the desired fields.

String datastr = inicio.getText().toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date inifer = new Date();
try
{
    inifer = dateFormat.parse(datastr);
}
catch (ParseException e)
{
    e.printStackTrace();
}
Log.i("Data de início", dateFormat.format(inifer));
int diafer = Integer.parseInt(diasfer.getText().toString());
Log.i("dias de férias", String.valueOf(diafer));

Calendar c = Calendar.getInstance();
Date terfer = inifer;
c.setTime(terfer);
c.add(c.DATE, diafer - 1);
// Não necessário terfer é atualizado por referência
//terfer.setTime(c.DATE);
int mester = c.get(Calendar.MONTH);
int diater = c.get(Calendar.DAY_OF_MONTH);
Log.i("mês de término férias", String.valueOf(mester));
Log.i("dia de término férias", String.valueOf(diater));

Browser other questions tagged

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