如何在对话框中添加小时和分钟以及日期以供用户选择?

时间:2018-02-09 05:15:26

标签: java android firebase

我想让用户选择日期和时间,我已经完成了日期,但我不知道如何写小时和分钟让用户选择日期和时间。

这是我的setDateTimeField

 private void setDateTimeField() {


    DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {



        @Override
        public void onDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int selectedDate) {

            year = selectedYear;
            month = selectedMonth;
            day = selectedDate;

            addtime.setText(new StringBuilder().append(year).append("-")
                    .append(month + 1).append("-").append(day));
        }
    },year, month, day);

    final Calendar calendar = Calendar.getInstance();
    Calendar cal = Calendar.getInstance();
    int yy = calendar.get(Calendar.YEAR);
    int mm = calendar.get(Calendar.MONTH);
    int dd = calendar.get(Calendar.DAY_OF_MONTH);

    cal.set(Calendar.MONTH, mm);
    cal.set(Calendar.DAY_OF_MONTH, dd);
    cal.set(Calendar.YEAR, yy);


    datePickerDialog.getDatePicker().setMinDate(cal.getTimeInMillis());
    datePickerDialog.show();
}

1 个答案:

答案 0 :(得分:0)

DatePicker非常适合年,月和日,但如果您还要设置小时和分钟,则需要查看TimePicker类。请参阅文档链接here以获取参考。

示例如下所示:

    Calendar cal = Calendar.getInstance();
    TimePickerDialog d = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int i, int i1) {
                    int hour = i;
                    int minute = i1;
                    //Utilize the fields here

            }
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), false);
    d.show();