Android: Date and Time Picker pop-up code example

On class level declare the following vars in your Activity:

private int mYear;
private int mMonth;
private int mDay;
private int mHour;
private int mMinute;
private Calendar c;
private Context ctx = this;

In the OnCreate, initialize them:

mYear= Calendar.getInstance().get(Calendar.YEAR);
mMonth=Calendar.getInstance().get(Calendar.MONTH)+1;
mDay=Calendar.getInstance().get(Calendar.DAY_OF_MONTH) ;
mHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) ;
mMinute = Calendar.getInstance().get(Calendar.MINUTE);

To get the Date Picker, call the following function:

private void show_Datepicker() {
  c = Calendar.getInstance();
  int mYearParam = mYear;
  int mMonthParam = mMonth-1;
  int mDayParam = mDay;

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

    @Override
    public void onDateSet(DatePicker view, int year,
      int monthOfYear, int dayOfMonth) {
        mMonth = monthOfYear + 1;
        mYear=year;
        mDay=dayOfMonth;
      }
    }, mYearParam, mMonthParam, mDayParam);
  
  datePickerDialog.show();
}

This will give you the date picker pop-up.

To get a Time Picker, call the following function:

private void show_Timepicker() {

  TimePickerDialog timePickerDialog = new TimePickerDialog(ctx,
  new TimePickerDialog.OnTimeSetListener() {

  @Override
  public void onTimeSet(TimePicker view, int pHour,
    int pMinute) {

      mHour = pHour;
      mMinute = pMinute;
    }
  }, mHour, mMinute, true);

  timePickerDialog.show();
}

That will give you the time picker pop-up.

Leave a Reply