LorenzoBerti LorenzoBerti - 4 months ago 24
Android Question

set format month datePicker extends dialogFragment

How Can i format month of

DatePicker
on
DialogFragment
?
I've created this class that extends
DialogFragment
:

DatePickerCustom

public class DatePickerCustom extends DialogFragment
implements DatePickerDialog.OnDateSetListener {


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

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);
month = month+1;

return new DatePickerDialog(getActivity(), this, year, month, day);
}


public void onDateSet(DatePicker view, int year, int month, int day) {
TextView datePickerText = (TextView)getActivity().findViewById(R.id.date_picker_text);
datePickerText.setText(day+" - "+month+" - "+year);

}
}


In my activity i've created a function that show
DatePicker
when i touch icons or
TextView
:

public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerCustom();
newFragment.show(getFragmentManager(), "datePicker");

}


In display I see date like: 22 - 7 - 2016 but i would have this format: 22 - 07 - 2016 so with 0 before month if it's < of 10

How can I do this?

Answer

You could do something like this:

public void onDateSet(DatePicker view, int year, int month, int day) {
    TextView datePickerText = (TextView) getActivity().findViewById(R.id.date_picker_text);

    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, day);

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String dateString = dateFormat.format(calendar.getTime());

    datePickerText.setText(dateString);
}
Comments