Android time picker example

In Android, you can use “android.widget.TimePicker” class to render a time picker component to select hour and minute in a pre-defined user interface.

In this tutorial, we show you how to render time picker component via android.widget.TimePicker in current page, and also in dialog box via android.app.TimePickerDialog. In addition, we also show you how to set a hour and minute in time picker component.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. TimePicker

Open “res/layout/main.xml” file, add time picker, label and button for demonstration.

File : res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnChangeTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Time" />

    <TextView
        android:id="@+id/lblTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Current Time (H:M): "
        android:textAppearance="?android:attr/textAppearanceLarge" />
  
    <TextView
        android:id="@+id/tvTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TimePicker
        android:id="@+id/timePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

P.S The “TimePickerDialog” is declare in code, not XML.

2. Code Code

Read the code’s comment, it should be self-explanatory.

File : MyAndroidAppActivity.java


package com.mkyong.android;

import java.util.Calendar;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class MyAndroidAppActivity extends Activity {

	private TextView tvDisplayTime;
	private TimePicker timePicker1;
	private Button btnChangeTime;

	private int hour;
	private int minute;

	static final int TIME_DIALOG_ID = 999;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		setCurrentTimeOnView();
		addListenerOnButton();

	}

	// display current time
	public void setCurrentTimeOnView() {

		tvDisplayTime = (TextView) findViewById(R.id.tvTime);
		timePicker1 = (TimePicker) findViewById(R.id.timePicker1);

		final Calendar c = Calendar.getInstance();
		hour = c.get(Calendar.HOUR_OF_DAY);
		minute = c.get(Calendar.MINUTE);

		// set current time into textview
		tvDisplayTime.setText(
                    new StringBuilder().append(pad(hour))
                                       .append(":").append(pad(minute)));

		// set current time into timepicker
		timePicker1.setCurrentHour(hour);
		timePicker1.setCurrentMinute(minute);

	}

	public void addListenerOnButton() {

		btnChangeTime = (Button) findViewById(R.id.btnChangeTime);

		btnChangeTime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				showDialog(TIME_DIALOG_ID);

			}

		});

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG_ID:
			// set time picker as current time
			return new TimePickerDialog(this, 
                                        timePickerListener, hour, minute,false);

		}
		return null;
	}

	private TimePickerDialog.OnTimeSetListener timePickerListener = 
            new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int selectedHour,
				int selectedMinute) {
			hour = selectedHour;
			minute = selectedMinute;

			// set current time into textview
			tvDisplayTime.setText(new StringBuilder().append(pad(hour))
					.append(":").append(pad(minute)));

			// set current time into timepicker
			timePicker1.setCurrentHour(hour);
			timePicker1.setCurrentMinute(minute);

		}
	};

	private static String pad(int c) {
		if (c >= 10)
		   return String.valueOf(c);
		else
		   return "0" + String.valueOf(c);
	}
}

P.S The “TimePickerDialog” example above, is referenced from Google Android time picker example, with some minor change.

3. Demo

Run the application.

1. Result, “time picker” and “textview” are set to current time.

android timepicker demo1

2. Click on the “Change Time” button, it will prompt a time picker component in a dialog box via TimePickerDialog.

android timepicker demo2

3. Both “time picker” and “textview” are updated with selected time.

android timepicker demo3

Download Source Code

Download it – Android-TimePicker-Example.zip (16 KB)

References

  1. Android TimePicker Example
  2. Android TimePicker JavaDoc
  3. Android TimePickerDialog JavaDoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Winney
Guest
Winney

Thanks for the great article. But, is there a way to show only specific time in time picker, eg: I want to show only PM hours (1PM-10PM) ?

hagai levi
Guest
hagai levi

it’s not work becuse The method showDialog(int) from the type Activity is deprecated
showDialog(TIME_DIALOG_ID);
can you show me how to fix that?

ekky
Guest
ekky

very usefull article. thank you so much….

Deal-or-die
Guest
Deal-or-die

Interested how I’m able to make the picker only visible in the dialog and not the main.xml. Any ideas? Cheers!

Deal-or-die
Guest
Deal-or-die

Wow… I apologise for my stupidity. Worked it out :P :P

I do have another question though… If I was to make 2 picker dialogs in the one main.java how would I do so?

Deal-or-die
Guest
Deal-or-die

Haha okay never mind that… Figured that out too… :P

Now I just have to get the 2 times selected by the pickers and calculate how many hours have passed… :/ And Ideas? Cheers!

Sulaiman Khan
Guest
Sulaiman Khan

Nice and easy to understand…

saeid
Guest
saeid

how send sms with time picker and date picker?
my mean user set time and date,after that sms sent when user set the time

pooja mehta
Guest
pooja mehta

How to compare start time and end time . I have taken button and edittext box as backgound of button

Mayaa
Guest
Mayaa

Perfect thanks… This http://www.compiletimeerror.com/2013/07/time-picker-in-android-example.html looks a bit different, may help.. Have a look…

rameshbabu
Guest
rameshbabu

sir.. how the time setup will open, while click on the change time button..

there is no button on click in xml file.. how was it work…

Denisia
Guest
Denisia

You, sir, are a real blessing !Great tutorial ,very useful and straight to the point!
Best regards!

martha
Guest
martha

este sitio me ayudo a resolver muchas dudas, gracias por su tiempo, y siga adelante, EXITOS :-)

trackback
Is there a way to get the time of the TimePicker without using the TimePickerDialog? | BlogoSfera

[…] I want to know if there is a way to get the time that the user has set in a TimePicker on the screen without using a Dialog. I don’t see the point in creating a button that will pop up a TimePickerDialog when I can just have the TimePicker on the screen. I.e. There is no point in having two TimePickers as can be seen in this tutorial and many other similar TimePicker tutorials: http://www.mkyong.com/android/android-time-picker-example/ […]

trackback
Is there a way to get the time of the TimePicker without using the TimePickerDialog? : Android Community - For Application Development

[…] I want to know if there is a way to get the time that the user has set in a TimePicker on the screen without using a Dialog. I don’t see the point in creating a button that will pop up a TimePickerDialog when I can just have the TimePicker on the screen. I.e. There is no point in having two TimePickers as can be seen in this tutorial and many other similar TimePicker tutorials: http://www.mkyong.com/android/android-time-picker-example/ […]

mathi
Guest
mathi

i like code to execute

duc
Guest
duc

Many thanks for all tutorials you have made, i learned many things from here. I also create a tutorial about how to customize a DateTimePicker Dialog at here. I hope this helpful for someone.
http://custom-android-dn.blogspot.com/2013/03/how-to-create-custom-date-time-picker.html

Shajeel Afzal
Guest
Shajeel Afzal

When i change the time in the dialog i get the Hour in 24 format. But i want to get it in the AM/PM format. I have passed false in the last argument of the TimePickerDialog constructor.

Gurinder
Guest
Gurinder

Try setting: timePicker.setIs24HourView(false);

Here the full blog post with a more up-to-date version http://www.ahotbrew.com/android-timepicker-example/

Namdev
Guest
Namdev

Hi sir,
I want develop the application in adroid that takes the call log information from the phone and I want to send that information to the server.So how I can develop this application.please give me the answer….

Plugie
Guest
Plugie

how about if the user should input duration.
for example 25 hours 5 minutes.

is there any example for duration picker ?

Qadir
Guest
Qadir

this is possible by using the mili seconds in Date class. first you have to convert the 25hrs and 5 minuts in mili seconds. then u will set the duration in miliseconds. hope the answer of question. :)

Sana
Guest
Sana

hi , i’m trying to put 2 time pickers in my android application to have the time of begin and end of a thread.. but i don’t know witch code to duplicate to do that .. please help !!

varsha
Guest
varsha

your apps is nice but i need your help.
i want to set a start date and end date with the same datepicker.
what should i do? Please help me.I am waiting for your reply.please reply as soon as possible..thank u again

Qadir
Guest
Qadir

you should show time and date picker in an alert dialog.
in alert dialog you have to create a time and date picker dynamically via codding (not using XML drag and drop) and two buttons OK and CANCEL.
one your dialog in triggered u will enter your start date, after that u will definatly click on the OK button, now here u can show a new date and time picker on the click event of OK button..

sojitra.sagar
Guest
sojitra.sagar

Its very easy to do so…just call this method

showDialog(TIME_DIALOG_ID);
and make sure conversation with variables that u r passing in it… if you get mistake then ur both time will be same… or may be interchange…

bob
Guest
bob

Very Bad

showDialog(TIME_DIALOG_ID);

Qadir
Guest
Qadir
shima
Guest
shima

i use the code but the time dont change with time of system and remaning.

ddkstudent
Guest
ddkstudent

Very simple, thank you!

shardul
Guest
shardul

Its beautiful site. I like your easy to go android tutorials. Thanks for your time…

trackback
Android analogclock and digitalclock example

[…] and DigitalClock are UNABLE to modify the time, if you want to change the time, use “TimePicker” instead. […]