设置格式月DatePicker扩展DialogFragment

时间:2016-07-22 14:37:12

标签: android android-datepicker

如何在DatePicker上格式化DialogFragment的月份? 我创建了这个扩展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);

   }
}

在我的活动中,当我触摸图标或DatePicker时,我创建了一个显示TextView的功能:

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

}

在显示中我看到日期如:22 - 7 - 2016但我会有这样的格式:22 - 0 7 - 2016所以如果它是<那么月前是0 10个

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用Date从您的值中创建Calendar对象,并使用适当的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);
}