从EditText
设置DatePicker
中的值时,如何设置为25-03-2014而不是25-3-2014。
它显示25-3-2014,缺少' 0'每月之前(mm)。
感谢。
答案 0 :(得分:1)
YourEditText = (EditText) findViewById(R.id.your_edittext);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date = sdf.format(new Date(System.currentTimeMillis()));
if (date.contains("/")) {
date = date.replace("/", "-");
}
YourEditText.setText(date);
在xml:
中的YourEditText上添加Click事件 android:onClick="onTime"
代码段:
请从Activity
FragmentActivity
public void onTime(View v) {
DialogFragment newFragment = new FromDatePickerFragment();
newFragment.show(getSupportFragmentManager(), "From Date");
}
class FromDatePickerFragment extends DialogFragment implements
OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int yr = c.get(Calendar.YEAR);
int mnth = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of TimePickerDialog and return it
return new DatePickerDialog(getActivity(), this, yr, mnth, day);
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
String date;
monthOfYear++;
if (dayOfMonth < 10) {
date = "0" + dayOfMonth + "-";
} else {
date = dayOfMonth + "-";
}
if (monthOfYear < 10) {
date += "0" + monthOfYear + "-";
} else {
date += monthOfYear + "-";
}
date += year;
YourEditText.setText(date);
}
}
答案 1 :(得分:0)
您可以使用SimpleDateFormat
作为&#34; dd / MM / yyyy&#34;。
查看文档。
http://developer.android.com/reference/java/text/SimpleDateFormat.html
答案 2 :(得分:0)
使用下面给出的代码可以解决你的问题...
DatePicker dp = (DatePicker)dialog.findViewById(R.id.datePicker1);
dp.getDayOfMonth();
dp.getMonth();
dp.getYear();
if(dp.getMonth()+1<10)
editText.setText(dp.getDayOfMonth()+"-"+"0"+(dp.getMonth() + 1 )+"-"+dp.getYear());
if(dp.getDayOfMonth()<10)
editText.setText("0"+dp.getDayOfMonth()+"-"+(dp.getMonth() + 1 )+"-"+dp.getYear() );
if(dp.getMonth()+1<10 && dp.getDayOfMonth()<10)
editText.setText("0"+dp.getDayOfMonth()+"-"+"0"+(dp.getMonth() + 1 )+"-"+dp.getYear() );
if(dp.getMonth()+1>9 && dp.getDayOfMonth()>9)
editText.setText( dp.getDayOfMonth()+"-"+(dp.getMonth() + 1 )+"-"+dp.getYear());
dialog.dismiss();
答案 3 :(得分:0)
简单地说就是这样,
final String DATE_FORMAT = "dd-MM-yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);