0

I want to let the user pick the date and the time, I've finished the date but I don't know how to write hours and minutes to let the user choose date and time.

Here is my 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();
}
Mark
  • 39
  • 8

1 Answers1

0

The DatePicker is ideal for year, month, and day, but if you want to also set hours and minutes, you will want to look into the TimePicker class. See the documentation link here for reference.

A Sample would look like this:

    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();
PGMacDesign
  • 6,092
  • 8
  • 41
  • 78
  • So the TimePickerDialog can also put in `setDateTimeField()` ? – Mark Feb 09 '18 at 05:51
  • I'm not sure I understand your question, Mark; can you elaborate? Do you mean, how do you set the default time for the dialog? Or something else? – PGMacDesign Feb 09 '18 at 15:13
  • I mean can the TimePickerDialog can also put in the same class with DatePickerDialog? – Mark Feb 10 '18 at 17:31
  • Yes, you absolutely can do that. The easiest way would be to put the code I showed above within the onDateSet method within your datePickerDialog. Right after your code to addtime.setText(), just make a new dialog for the time and you will first get the date, then the time. This is just one of many ways to do it. – PGMacDesign Feb 11 '18 at 03:21
  • Oh, I see, thanks for your help :) – Mark Feb 11 '18 at 05:13