设置格式月 DatePicker extends DialogFragment

Set format month DatePicker extends DialogFragment

如何在 DialogFragment 上设置 DatePicker 月份的格式? 我创建了这个扩展 DialogFragment:

的 class

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);

   }
}

在我的 activity 中,我创建了一个功能,当我触摸图标或 TextView:

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

}

在显示中,我看到日期如下:22 - 7 - 2016 但我会采用这种格式:22 - 07 - 2016 所以如果月份小于 10,则在月份之前加上 0

我该怎么做?

您可以使用 Calendar 从您的值创建一个 Date 对象,并使用适当的 SimpleDateFormat 实例对其进行格式化。

像这样:

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);
}