Time Picker Dialog Example in Android

Many time we need to get Time from user, this done by Time Picker dialog. By using android.widget.TimePicker class we able to use Time Picker Dialog.

Time Picker allows us to select the time of day in either 24 hour or AM/PM mode. Let’s see simple code for Time picker.

Make simple activity_main.xml with one button to open Time Picker, two TextView for show both time format time.

Now first in Java file we have to make onCreateDialog( int id )  for create dialog. Just like ,

Here TIME_PICKER_DIALOG_ID is unique id of Dialog, if we want to make more that one dialog we can specify and separate by ID.

TimePickerDialog(Context, OnTimeSetListener, int hourOfDay, int minute, boolean is24HourView);

Context : Context of Activity.
OnTimeSetListener : Listener for get time when set
hourOfDay : Hour of the Day( current hour)
minute : Minute of current hour
is24HourView : boolean to show Time in 12 Hour format or 24 Hour format.

Now create OnTimeSetListener like below,

You can do whatever you want in this listener when user set time and you get time in 24 hour format. In this tutorial you also learn how to convert 24 Hour in 12 Hour AM/PM  format.

Let’s see full code.


MainActivity.java file


In last function convertTo12HourFormat(hour,minute) you can convert time into 12 hour AM/PM format.

Now run project. Our Output looks like below,


Download Project.

(Visited 910 times, 1 visits today)