How to compare dates?

Asked

Viewed 48 times

-1

I created an NN/NN/NNNN mask in my editText to capture due date, without a calendar, all done in edt. Then I used Simpledateformat to capture the current system date. I made a comparison with the edt mask and the varialvel (current date) of the simpledateformat. But I think the comparison is not working. The created condition does not appear. I type the current date, but there is no "test" (condition I created as a test).

Field mask

 final EditText edtDataSelecionada = (EditText) findViewById(R.id.edtDataSelecionada);

    //Criando a mascara de campo
    SimpleMaskFormatter smf = new SimpleMaskFormatter("NN/NN/NNNN");
    MaskTextWatcher mtw = new MaskTextWatcher(edtDataSelecionada, smf);
    edtDataSelecionada.addTextChangedListener(mtw);
    //fim da mascará

Simpledateformat and condition

item.setDataselecionada(String.valueOf(edtDataSelecionada.getText().toString().trim()));

                SimpleDateFormat formataData = new SimpleDateFormat("dd/MM/yyyy");
                Date data = new Date();
                String dataFormatada = formataData.format(data);


                if (edtDataSelecionada.getText().toString() == dataFormatada){
                    item.setNotificacao("Teste");
                }

Another thing, I’d like to make comparisons with the separate dd of the MM.

  • The method format of a SimpleDateFormat returns a String. And in Java, strings must be compared with equals, not with the operator ==. Then just do if (edtDataSelecionada.getText().toString().equals(dataFormatada)) { etc... }

1 answer

0

I’m not sure I quite understood your question, but basically to compare a date you’d have to turn edtDataSelecionada for an object Date and then use the function compareTo.

Example:

SimpleDateFormat formataData = new SimpleDateFormat("dd/MM/yyyy");
Date data = new Date();
String dataFormatada = formataData.format(data);

Date d1 = formataData.parse(edtDataSelecionada.getText().toString());
Date d2 = formataData.parse(dataFormatada);


if (d1.compareTo(d2) == 0){
    item.setNotificacao("Teste");
}

Or else with equals:

if (d1.equals(d2)){
    item.setNotificacao("Teste");
}

Take a look here

  • Exactly that, I was able to do the conversion from String to Date. But I have a problem, I put the same code in onResume of the screen that is my list, so that messages are passed with the update of the current date. Date D1 = null; Try { D1 = formatData.parse(item.getDataselected();// this.getDataselected item is in error. } catch (Parseexception e) { e.printStackTrace(); }error: Caused by: java.lang.Nullpointerexception: Attempt to invoke virtual method 'int java.lang.String.length()' on a null Object Reference

  • In case it seems you are now with an error in this method "getDataselected" same.

Browser other questions tagged

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