Search code examples
androidsimpledateformatdatepickerdialog

Change DateFormat from DatePickerDialog using SimpleDateFormat in Android


I'm new to Java and Android. I took the following code from different Tutorials on DatePickerDialog (mainly the official one). Now I want the selected date to be in a specific format ("EE, DD.MM.YY") and tried to do this with SimpleDateFormat but I don't understand where to get the selected date from since I "only" have year, month and day as arguments:

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    public Date date;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        date = c.getTime();

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);

    }

    public void onDateSet(DatePicker view, int year, int month, int day) {

        TextView textView = (TextView) getActivity().findViewById(R.id.textView_Date);

        String selectedDate = String.valueOf(day) + "." + String.valueOf(month) + "." + String.valueOf(year);
        textView.setText(selectedDate);
    }

}

So I tried to change the line

String selecteDate = ...

into something like

SimpleDateFormat simpledateformat = new SimpleDateFormat("EE, DD.MM.YY");
String selectedDate = simpledateformat.format(date);

But since "date" is not the selected one but the current one and because the result of simpledateformat.format is probably not a String, it doesn't work. Can anyone tell me how to make it work? It doesn't need to be SimpleDateFormat though, that's just the way I thought it might work. Thanks a lot!


Solution

  • Try this:

    SimpleDateFormat simpledateformat = new SimpleDateFormat("EE, dd.MM.yy");
    Calendar newDate = Calendar.getInstance();
    newDate.set(year, month, day);
    String selectedDate = simpledateformat.format(newDate.getTime());