如何在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个
我该怎么做?
答案 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);
}