这是我的代码,它以这种格式显示日期15 8 2013,但如果月份或日期为单数,则我想以双位数显示,如果日期为8,则显示为08;如果月份为8,则显示为08。如果要确定月份和日期的条件是否有任何快速方法或for循环来检测单个字符,然后再加上0,则不想添加9次?

like if (mday=1) {
         mday=01
     }

     if (mday=2) {
          mday=02
     }

     if (mMonth=2) {
          mMonth =02
     }

     if (mMonth=2) {
          mMonth =02
     }

int completedate2;

    Calendar mCalendar = Calendar.getInstance();
    mYear = mCalendar.get(Calendar.YEAR);
    mMonth = mCalendar.get(Calendar.MONTH) + 1;
    mDay = mCalendar.get(Calendar.DAY_OF_MONTH);

     Toast.makeText(this, "current date is" +mDay+mMonth+mYear,
       Toast.LENGTH_SHORT).show();
     completedate2=mDay+mMonth+mYear;

最佳答案

String.format("%02d", mday)


应该为您将数字格式化为两位数,如果为一位,则以0开头。

Toast.makeText(this, "current date is" +String.format("%02d", mday)+String.format("%02d", mMonth)+mYear, Toast.LENGTH_SHORT).show();


编辑:

 String completedate2 = String.format("%02d", mday) + String.format("%02d", mMonth) + mYear;

07-26 07:32