Browse By

Date Picker Dialog and Time Picker Dialog in Android

Date Picker Dialog and Time Picker Dialog  in Android use to select a date and time, as it will be popup when you needed.  While Time Picker  and Date Picker  widget occupy more space on screen. Dialogs are best way to solve this issue.

Dialog box used to show some information or prompt  user to do some kind of action. In Android, we have many different  dialog types. Each has special function that most users should be somewhat familiar with it. In Pulse 7 we will discuss below dialog box in depth.

  1.  Dialog
  2. Alert Dialog
  3. Progress Dialog
  4. Date Picker Dialog
  5. Time Picker Dialog

 

In this tutorial, we will learn how to show Date Picker Dialog box and Time Picker Dialog Box in Android Application. In this Application we will have simple screen where we will have two text box (one for date and one for time) and two buttons (one for launching date picker and one for launching time picker). When user click on button it will display respective dialog. When user select date or time, it will be visible on text box.

Direct Download Full Source Code

 

 

Date Picker Dialog

Let’s first see how to launch Date Picker Dialog. We will use DatePickerDialog class, we will use 5 argument constructor, listed below:

  1. Context , it will be application context
  2. Callback function, used when user select date
  3. int for Year, which will be visible as selected Year on calendar
  4. int for Month, which will be visible as selected month on Date Picker Dialog
  5. int for Day, which will be visible as selected day on Date Picker Dialog.
			final Calendar c = Calendar.getInstance();
			mYear = c.get(Calendar.YEAR);
			mMonth = c.get(Calendar.MONTH);
			mDay = c.get(Calendar.DAY_OF_MONTH);

			DatePickerDialog dpd = new DatePickerDialog(this,
					new DatePickerDialog.OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view, int year,
								int monthOfYear, int dayOfMonth) {
							txtDate.setText(dayOfMonth + "-"
									+ (monthOfYear + 1) + "-" + year);

						}
					}, mYear, mMonth, mDay);
			dpd.show();
Date Picker Dialog

Date Picker Dialog

Time Picker Dialog

Now let’s see how to display Time Picker Dialog in Android Application. We will use TimePickerDialog class, we will use 5 argument constructor, listed below:

  1. Context , it will be application context
  2. Callback function, used when user select date
  3. int for Hour, which will be visible as selected hour in Time Picker Dialog
  4. int for Minutes, which will be visible as selected minutes in Time Picker Dialog
  5. boolean value to set 24 Hour format or not.
			TimePickerDialog tpd = new TimePickerDialog(this,
					new TimePickerDialog.OnTimeSetListener() {

						@Override
						public void onTimeSet(TimePicker view, int hourOfDay,
								int minute) {
							txtTime.setText(hourOfDay + ":" + minute);
						}
					}, mHour, mMinute, false);
			tpd.show();

 

Time Picker Dialog

Time Picker Dialog

Below is full source code with xml file.

Create New Android Project

  1. Create a new project and fill the required details File ⇒ New ⇒ Android Project
  2. Now open main.xml (res/layout) and create simple GUI with two textbox and two button for date and time picker dialog.
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    	android:orientation="vertical" android:layout_width="fill_parent"
    	android:layout_height="fill_parent">
    	<TextView android:textColor="#fff" android:textSize="20dp"
    		android:layout_height="wrap_content" android:id="@+id/textView1"
    		android:text="Pulse 7 Demo" android:layout_width="wrap_content"
    		android:layout_gravity="center_horizontal" android:paddingTop="10dp"
    		android:paddingBottom="10dp"></TextView>
    	<TextView android:textColor="#fff" android:textSize="20dp"
    		android:layout_height="wrap_content" android:id="@+id/textView2"
    		android:text="Date and Time Picker Dialog" android:layout_width="wrap_content"
    		android:layout_gravity="center_horizontal" android:paddingTop="5dp"
    		android:paddingBottom="25dp"></TextView>
    	<LinearLayout android:layout_width="match_parent"
    		android:layout_height="wrap_content" android:id="@+id/linearLayout1">
    		<EditText android:layout_width="wrap_content"
    			android:layout_height="wrap_content" android:layout_weight="1"
    			android:id="@+id/txtDate">
    			<requestFocus></requestFocus>
    		</EditText>
    		<Button android:layout_height="wrap_content"
    			android:layout_weight="0" android:id="@+id/btnCalendar" android:text="Calendar"
    			android:layout_width="100dp"></Button>
    	</LinearLayout>
    	<LinearLayout android:layout_width="match_parent"
    		android:layout_height="wrap_content" android:id="@+id/linearLayout1">
    		<EditText android:layout_width="wrap_content"
    			android:layout_height="wrap_content" android:layout_weight="1"
    			android:id="@+id/txtTime">
    			<requestFocus></requestFocus>
    		</EditText>
    		<Button android:layout_height="wrap_content"
    			android:layout_weight="0" android:id="@+id/btnTimePicker"
    			android:text="Time Picker" android:layout_width="100dp"></Button>
    	</LinearLayout>
    </LinearLayout>
  3. Now let’s put Date Picker Dialog box  and Time Picker Dialog box code in Activity class. When user click on button, it should display respective Dialog box .
    package com.vrs.pulse7.datepickerdialog;
    
    import java.util.Calendar;
    
    import android.app.Activity;
    import android.app.DatePickerDialog;
    import android.app.TimePickerDialog;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.DatePicker;
    import android.widget.EditText;
    import android.widget.TimePicker;
    
    public class Pulse7DatePickerDialogActivity extends Activity implements
    		OnClickListener {
    
    	// Widget GUI
    	Button btnCalendar, btnTimePicker;
    	EditText txtDate, txtTime;
    
    	// Variable for storing current date and time
    	private int mYear, mMonth, mDay, mHour, mMinute;
    
    	/** Called when the activity is first created. */
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    
    		btnCalendar = (Button) findViewById(R.id.btnCalendar);
    		btnTimePicker = (Button) findViewById(R.id.btnTimePicker);
    
    		txtDate = (EditText) findViewById(R.id.txtDate);
    		txtTime = (EditText) findViewById(R.id.txtTime);
    
    		btnCalendar.setOnClickListener(this);
    		btnTimePicker.setOnClickListener(this);
    	}
    
    	@Override
    	public void onClick(View v) {
    
    		if (v == btnCalendar) {
    
    			// Process to get Current Date
    			final Calendar c = Calendar.getInstance();
    			mYear = c.get(Calendar.YEAR);
    			mMonth = c.get(Calendar.MONTH);
    			mDay = c.get(Calendar.DAY_OF_MONTH);
    
    			// Launch Date Picker Dialog
    			DatePickerDialog dpd = new DatePickerDialog(this,
    					new DatePickerDialog.OnDateSetListener() {
    
    						@Override
    						public void onDateSet(DatePicker view, int year,
    								int monthOfYear, int dayOfMonth) {
    							// Display Selected date in textbox
    							txtDate.setText(dayOfMonth + "-"
    									+ (monthOfYear + 1) + "-" + year);
    
    						}
    					}, mYear, mMonth, mDay);
    			dpd.show();
    		}
    		if (v == btnTimePicker) {
    
    			// Process to get Current Time
    			final Calendar c = Calendar.getInstance();
    			mHour = c.get(Calendar.HOUR_OF_DAY);
    			mMinute = c.get(Calendar.MINUTE);
    
    			// Launch Time Picker Dialog
    			TimePickerDialog tpd = new TimePickerDialog(this,
    					new TimePickerDialog.OnTimeSetListener() {
    
    						@Override
    						public void onTimeSet(TimePicker view, int hourOfDay,
    								int minute) {
    							// Display Selected time in textbox
    							txtTime.setText(hourOfDay + ":" + minute);
    						}
    					}, mHour, mMinute, false);
    			tpd.show();
    		}
    	}
    }
  4. Now let’s execute application.
    Date and Time Picker Screen

    Date and Time Picker Screen Click on button to display respective dialog box.

    Date Picker Dialog will be visible when you click on calendar button

    Date Picker Dialog will be visible when you click on calendar button

    Time Picker Dialog will be visible when you click on Time Button

    Time Picker Dialog will be visible when you click on Time Button

    Selected Date and Time will be visible on screen.

    Selected Date and Time will be visible on screen.

     

I hope you like this article. Share your views to to improve content.

Download Full Source Code

 

 

  • Pingback: Login Dialog Box in Android | Pulse7()

  • Jena Sookdin Reshmeebye

    gr8 tuto :) i tried to save date in the db and it works :) thnks

    • Mike

      Hello how do i save the date and time into the data base?

      • http://virtualrealitysystems.net/ Vimal Rughani

        Hi Mike, First you have to convert your date into “yyyy-MM-dd HH:mm:ss” format using SimpleDateFormat class and then save it into database.
        Let me know if you find any difficulty.

        • Mike

          Hi Sir,

          Thanks for your help!

          I am new to android development and I managed to save it into my database (using my own inefficient and more extensive code).

          Can i ask you some questions about databases?

          Is a SQLite database only accessible for 1 user/device? For example, if i have a database that has information to be accessed by many users all over the world, what kind of database should i use to store the date and time data?

          Thanks in advance for your help.

          • http://virtualrealitysystems.net/ Vimal Rughani

            Hi Mike,

            For sharing data with more devices, you have to store your data into webserver or cloud instead of local SQLite database. Other devices will fetch from webserver or cloud. If you want to work with parse cloud in android application, you can check my this article. http://pulse7.net/android/integrating-parse-sdk-cloud-based-services-android-application/

            Please feel free for your queries.

          • Mike

            Thanks! I have successfully implemented the parse cloud! I only have a problem now, the parse database converts my date variable according to the server time.

            In addition, do you have a tutorial on how to implement Facebook login in android? I am facing many errors about the JAR dependencies.

  • Anand Kumar

    Nice code

  • shefin

    In a datepicker dialog there are two buttons set and cancel….how can we remove cancel button or give action in it??

  • Zain Imtiaz

    It gives error and do not shows the time picker dialog! What should i do now? :(

    • http://virtualrealitysystems.net/ Vimal Rughani

      Please send me logcat for that error, so I can know better.

      • Zain Imtiaz

        Problem resolved sir. Thank u for your quick response.

    • Shabnam Ahmmed

      Hey Zain imtiaz, did u get solution. Mine also giving error.saying “Unable to add window token…. “

      • Shabnam Ahmmed

        my problem is solved.In “DatePickerDialog dpd = new DatePickerDialog(this,
        new DatePickerDialog.OnDateSetListener(){…}” line i replaced this with Activity.this.

        • Zain Imtiaz

          Sry for late reply dear. I was about to tell u the same thing :)

          Have a good day

  • chintan

    how can i get difference between two dates in android…its urgent

  • Pingback: android datepicker - android firmware download | android firmware download()

  • BhauMik

    Hello sir ! In My android app I want to set date of dialog datepicker from textview . it is possible ? If possible then how it is possible ? Please know me . I waiting for your reply .

  • Mario German Agudelo

    Hi Sir: Good video, I have the following question, I have an application where I want me to be the administrator of the calendar in which users enter and to request an appointment, but only I can accept and you get a message to users if it was or not accepted the appointment. I appreciate all your help and support.