Last Updated:

DatePickerDialog and TimePickerDialog in Android with Example

In this tutorial we will create a simple application with Date Picker and Time Picker Dialog. These components are used to select the date and time directly by the user. In code, they are implemented using the . and . Read more in the article below.DatePickerDialogTimePickerDialogCalendar

A quick tour of DatePickerDialog and TimePickerDialog in Android

Usually, the choice of date and time in Android is implemented using independent widgets, but individually they are inconvenient and take up more space on the screen, so they are more often used inside Dialog. The developers of the Android system noticed this and created convenient classes and accordingly for choosing the date and time.

DatePickerDialogTimePickerDialog

To interact with the user, each of these classes uses the callback and .onDateSetListener()onTimeSetListener()

 

There are as many as 5 parameters in the class constructor:DatePickerDialog

  1. Context is the context of the app
  2. Callback function: Called when the user sets a date with the following parameters: onDateSet()
    • int year — gets the selected year from the dialogue
    • int monthOfYear — stores the selected month from the dialog
    • int dayOfMonth — stores the selected day from the dialog
  3. int mYear is the year that is displayed when the dialog is created
  4. int mMonth — month
  5. int mDay – day

The class constructor also has 5 parameters:TimePickerDialog

  1. Context - Application context required
  2. Callback function: Called when the user sets the time with the following parameters: onTimeSet()
    • int hourOfDay – stores the selected hour of the day from the dialog
    • int minute — stores the selected minute from the dialog
  3. int mHours is the hour that is displayed when creating a dialog
  4. int mMinute is the minute that is displayed when creating a dialog
  5. boolean mBool — if false, then the time format is 24 hours, if true is 12 hours.

Practice. Creating a DatePickerDialog and TimePickerDialog in Android

 

There will be 2 Button widgets in the activity_main.xml layout: to call and . The date and time selected by the user will be saved in the appropriate fields:

DatePickerDialogTimePickerDialogEditText

The lines were moved to the strings file.xml:

In the MainActivity class, you need to initialize the listener and call the desired method depending on the button pressed:

The result of running the program to work with DatePickerDialog and TimePickerDialog in Android.

 

Stay tuned to the Android Programming section and subscribe to a new article on Java and Android.