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);
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() {

    public void onDateSet(DatePicker view, int year,
      int monthOfYear, int dayOfMonth) {
        mMonth = monthOfYear + 1;
    }, mYearParam, mMonthParam, mDayParam);;

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() {

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

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

That will give you the time picker pop-up.

Leave a Reply

Your email address will not be published. Required fields are marked *