Android Date Picker and Time Picker Example

Many times arises a need to take date and time input from user. Then starts a series of converting tedious date formats and shameless workarounds. This is a tutorial explaining how to use Date Picker and Time Picker in Android. It presents an aesthetic interface to user and provides data in standard format to programmer. Plus, its a good UI practice.

To present these dialogs, we will use DialogFragment to host them.

If you are a code-first tutorial-later person then you can have a look at sample project hosted on github.

Time Picker

To integrate Time Picker Dialog in your Activity you need to define an inner class like below.


public class TimePickerFragment extends DialogFragment implements
			TimePickerDialog.OnTimeSetListener {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current time as the default values for the picker
			final Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);

			// Create a new instance of TimePickerDialog and return it
			return new TimePickerDialog(context, this, hour, minute,
					DateFormat.is24HourFormat(context));
		}

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// Do something with the time chosen by the user
			
		}
	}



onCreateDialog returns our TimePicker dialog, we are initializing it with device’s current time. onTimeSet is called when a time is selected in dialog. We can do whatever we want to do with that time.

We can show this TimePicker Dialog on any event such as button click using following code.

DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getSupportFragmentManager(), "timePicker");

Look closely in onTimeSet we have hourOfDay, that will be in 24 hour format. To convert it into 12 hour format and display AM/PM we need to tweak it a bit as show below.

	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String AM_PM = "";

			Calendar datetime = Calendar.getInstance();
			datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
			datetime.set(Calendar.MINUTE, minute);

			if (datetime.get(Calendar.AM_PM) == Calendar.AM)
				AM_PM = "AM";
			else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
				AM_PM = "PM";

			String hours = (datetime.get(Calendar.HOUR) == 0) ? "12" : datetime
					.get(Calendar.HOUR) + "";
			
			Log.d(“Time: ”, hours + “ : ” + minute + “  ” + AM_PM );

}

Check out sample project hosted on github for full source code.

Date Picker

For using DatePicker, TimePicker like approach is used.

A class needs to be defined like below.

public class DatePickerFragment extends DialogFragment implements
			DatePickerDialog.OnDateSetListener {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int day = c.get(Calendar.DAY_OF_MONTH);

			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}

		public void onDateSet(DatePicker view, int year, int month, int day) {
			// Do something with the date chosen by the user

			/*
			 * MOnth returned from datepicker is always one less than actual
			 * value for example: December will be 11, January will be 0 and so
			 * on.
			 */

			month = month + 1;

			Log.d(“Date: ” , day + " - " + month + " - " + year); 

		}
	}


We can call it with following code.



DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");


In onCreateDialog we intialize our dialog with device’s current date. onDateSet is called when a date is selected in dialog.

Note that in onDateSet, month returned is one less than the actual month so we need to increment it by 1.

Check out full source code of sample project at github.

See it in action:

Date and Time Picker Android

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s