我的要求是当点击按钮然后打开日期选择器对话框并选择日期然后单击确定按钮时,所选日期将在编辑文本中显示。但我希望显示该日期有" 01-01-14"格式而不是1-1-14。请检查我的代码段 '
private String setdate() {
// TODO Auto-generated method stub
// Process to get Current Date
int fYear, fMonth, fDay;
final Calendar c = Calendar.getInstance();
fYear = c.get(Calendar.YEAR);
fMonth = c.get(Calendar.MONTH);
fDay = c.get(Calendar.DAY_OF_MONTH);
// Launch Date Picker Dialog
DatePickerDialog dpd = new DatePickerDialog(RemindMeDetails.this,
new DatePickerDialog.OnDateSetListener() {
@SuppressLint("SimpleDateFormat")
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
try{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String cdate = formatter.format(new Date());
Date Cdate = formatter.parse(cdate);
String date=(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year).toString();
/*String date=(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year).toString();*/
Date dateD = formatter.parse(date);
if (Cdate.compareTo(dateD)<=0){
onetime_edit_date.setText(date);
}
else{
showmessage("Alert", "date is not lower than current Date");
}
}catch (ParseException e1){
e1.printStackTrace();
}
}
}, fYear, fMonth, fDay );
dpd.show();
return cmn_date;
}
&#39;
答案 0 :(得分:3)
你需要的只是
Calendar cal = Calendar.getInstance();
c.set(year + 1900, monthOfYear, dayOfMonth);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy");
String cdate = formatter.format(c.getTime());
然后用
设置它onetime_edit_date.setText(cdate);
您不需要操作字符串的其余代码。
唯一需要注意的是月份字段是从0开始的:1月用零表示。因此,根据monthOfYear
参数的来源,您可能需要减去1。
请注意格式字符串中的yy
而不是yyyy
,以获得两位数的年份。
答案 1 :(得分:3)
尝试使用从onDateSetter接收的值设置日期。希望这有帮助
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
try{
Date date = new Date(year+1900, monthOfYear,dayOfMonth);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy");
String cdate = formatter.format(date);
}catch (ParseException e1){
e1.printStackTrace(); }
}
return cdate;
}
答案 2 :(得分:0)
使用日历实例存储年,月和日值
Calendar c=Calendar.getInstance();
c.set(Calendar.YEAR,year);
c.set(Calendar.MONTH,monthOfYear);
c.set(Calendar.DAY_OF_MONTH,dayOfMonth);
然后使用SimpleDateFormat格式化String输出
String out=formatter.format(c.getTime());