我在我的Android应用程序中遇到了一些奇怪的问题,当我选择日期为ex,15march2013在datepicker中我得到9october2007
这是来自sorces的片段
public static class DatePickerFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in 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);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), (OnDateSetListener)getActivity(), year, month, day);
}
}
public void onDateSet(DatePicker view, int year, int month, int day) {
d.setDate(day);
d.setMonth(month);
d.setYear(year);
int flags = 0;
flags |= DateUtils.FORMAT_SHOW_DATE;
flags |= DateUtils.FORMAT_SHOW_YEAR;
String str = DateUtils.formatDateTime(this, d.getTime(), flags);
date.setText(str);
}
实际上我没想到会出现什么问题
请帮助!
答案 0 :(得分:3)
不推荐使用这些调用:
d.setDate(day);
d.setMonth(month);
d.setYear(year);
并没有按照你的想法做。如果您通过每次通话追踪并观察d更改,您会惊讶地发现它只是将这些金额添加到自身。
你应该做这样的事情:
Calendar c = Calendar.getInstance();
c.set(year, month, day);
SimpleDateFormat df = new SimpleDateFormat("d yyyy MMM");
String formattedDate = df.format(c.getTime());
date.setText(str);
您可以在此处查看更多日期格式选项:
http://developer.android.com/reference/java/text/SimpleDateFormat.html
答案 1 :(得分:0)
我实现这一目标的方式:
public class AddEditCourseActivity extends Activity {
private Button classStartBT;
private DatePickerDialog mDatePickerDialog;
private Calendar classStartDate;
private SimpleDateFormat mDateFormatter;
@Override
protected void onCreate(Bundle savedInstanceState) {
classStartDate = new GregorianCalendar();
/** Initialize the mTimeFormatter object */
mTimeFormatter = new SimpleDateFormat("yyyy dd, MM");
classStartBT = (Button) findViewById(R.id.courseClassStartBT);
classStartBT.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDatePickerDialog = new DatePickerDialog(
MyActivity.this, mDateSetListener,
classStartDate.get(Calendar.YEAR),
classStartDate.get(Calendar.MONTH),
classStartDate.get(Calendar.DAY_OF_WEEK));
mDatePickerDialog.show();
} // end onClick
});
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
classStartTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
classStartTime.set(Calendar.MINUTE, minute);
/**
* display the "class start time" on the buttons
*/
classStartBT.setText(mDateFormatter.format(classStartTime.getTime()));
}
};
} // end activity