设置setMaxDate后如何显示当前日期?

时间:2019-04-11 05:57:36

标签: java android datepicker

我已将maxDate设置为今天日期,但它显示为1900年1月,我想将maxDate设置为Today,并在datepicker上显示今天日期,请帮忙。

shared-styles.html

1 个答案:

答案 0 :(得分:0)

尝试以下代码。.将以下代码放入onCreate方法..或单击按钮

Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
 int mDay = c.get(Calendar.DAY_OF_MONTH);

 DatePickerDialog dialog =
new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
 dialog.show();

//这在内部类中定义。      DatePickerDialog.OnDateSetListener mDateSetListener =新的DatePickerDialog.OnDateSetListener(){

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        // myCalendar your calendar object
        myCalendar.set(Calendar.YEAR, year);
        myCalendar.set(Calendar.MONTH, month);
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    }
};

尝试将其定义为类。

 Calendar myCalendar;
int mYear, mMonth, mDay;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.upload);
    Button selectUploadButton = (Button) findViewById(R.id.select_image);
    selectUploadButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            DatePickerDialog dialog =
                    new DatePickerDialog(MainActivity1.this, mDateSetListener, mYear, mMonth, mDay);
       dialog.getDatePicker().setMaxDate(System.currentTimeMillis());

            dialog.show();
        }
    });

    myCalendar = Calendar.getInstance();

    mYear = myCalendar.get(Calendar.YEAR);
    mMonth = myCalendar.get(Calendar.MONTH);
    mDay = myCalendar.get(Calendar.DAY_OF_MONTH);
}

DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        myCalendar.set(Calendar.YEAR, year);
        myCalendar.set(Calendar.MONTH, month);
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    }
};