datepicker和日历中的日期格式更改

时间:2013-01-04 08:46:22

标签: android android-layout android-intent android-emulator

如何将2/3/2013格式更改为02/03/2013 (dd/mm/yyyy)

 Calendar c1 = Calendar.getInstance();
    year = c1.get(Calendar.YEAR);
    month = c1.get(Calendar.MONTH);
    day = c1.get(Calendar.DAY_OF_MONTH);
//  formatter = new SimpleDateFormat("dd/MM/yyyy");


     public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;
            // set selected date into textview.
            searchText.setText(new StringBuilder().append(month + 1).append("/").append(day).append("/").append(year).append(" "));
            Log.i("DatePickerDialog","DatePickerDialog");
            dpResult = (DatePicker) findViewById(R.id.dpResult);
            // set selected date into datepicker also.
            dpResult.init(year, month, day, null);
            user.setSearchEntityType("ByDate");
        }       
    };

当前输出:

1/2/2013 
d/m/y

寻找:

01/02/2013
dd/mm/yyyy

4 个答案:

答案 0 :(得分:8)

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
        int dayOfMonth) {

    int month = monthOfYear + 1;
    String formattedMonth = "" + month;
    String formattedDayOfMonth = "" + dayOfMonth;

    if(month < 10){

        formattedMonth = "0" + month;
    }
    if(dayOfMonth < 10){

        formattedDayOfMonth = "0" + dayOfMonth;
    }
    searchText.setText(formattedDayOfMonth + "/" + formattedMonth + "/" + year);
}

答案 1 :(得分:4)

使用DateFormat课程。做这样的事情:

Calendar cal = Calendar.instance();
cal.set(year, month, day);
CharSequence output = DateFormat.format("MM/dd/yyyy", cal);

有关更多示例,请参阅here

答案 2 :(得分:1)

使用此代码获取dd / mm / yy等格式。

int month = monthOfYear + 1;
String formattedMonth = "" + month;
String formattedDayOfMonth = "" + dayOfMonth;
String formattedYear=String.valueOf(year);

if(month < 10){

   formattedMonth = "0" + month;
}
if(dayOfMonth < 10){

   formattedDayOfMonth = "0" + dayOfMonth;
}

formattedYear=formattedYear.substring(formattedYear.length()-2);
String date=formattedDayOfMonth + "/" + formattedMonth + "/" + formattedYear;
mEDDate.setText(date);

答案 3 :(得分:0)

简单,添加条件如下:

 if (month<10)
   month='0'+month;
 if (day<10)
   day='0'+day;