Date formatter not working

0

I have a code that supposedly passes to dd-mm-yyyy or for example 02-10-2017 but my problem is that this code instead of passing 02-10-2017 is going to 2-10-2017 .

Code:

dt = 2 + "-" + 10 + "-" + 2017;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
try {
    sdf.parse(dt);
    date_text.setText(dt);
    Log.d(tag,""+dt);
} catch (ParseException e) {
    e.printStackTrace();
}

In the log I have this result:

07-13 20:42:25.914 12020-12020/com.pedrogouveia.averagemaker D/tag: 2-10-2017

Updated code:

        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month = month + 1;
            date_button.setVisibility(View.GONE);
            date_text = (TextView) rootView.findViewById(R.id.date_text);
            date_text.setVisibility(View.VISIBLE);
            dt = day + "-" + month + "-" + year;
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            dataInterpetrada = sdf.format(dt);     <---------Esta linha  esta vermelha e esta dizendo incompatible types java.util.dates and java.lang.string 
            dt = sdf.format(dataInterpetrada);
            date_text.setText(dt);

        }
    };

More down to add my database as string

    
asked by anonymous 13.07.2017 / 22:33

1 answer

1

The parse of SimpleDateFormat returns the date that was interpreted.

Soon it's supposed to be something like:

Date dataInterpretada = sdf.parse(dt);

And if you want to write in Log with the previous format, you must use format of the same format object:

Log.d(tag,""+ sdf.format(dataInterpretada ));

Small test in java to confirm .

Completing the displayed code:

dt = 2 + "-" + 10 + "-" + 2017;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
try {
    Date dataInterpretada = sdf.parse(dt); //agora guarda a data interpretada
    date_text.setText(sdf.format(dataInterpretada )); //agora com format
    Log.d(tag,""+sdf.format(dataInterpretada )); //e aqui com format também
} catch (ParseException e) {
    e.printStackTrace();
}

Edit:

The SimpleDateFormat returns a date of type java.util.date and not java.sql.date . To solve this problem or change the import or you can only change the date creation by doing:

java.util.Date dataInterpretada = sdf.parse(dt);
    
13.07.2017 / 22:37