Android Time and Date picker tutorial

DatePicker widget

Android DatePicker provides a widget for selecting the date consisting of day, month and year in your custom user interface.

When the datePickerMode attribute is set to spinner, the date can be selected using year, month, and day spinners or a CalendarView. The set of spinners and the calendar view are automatically synchronized. The client can customize whether only the spinners, or only the calendar view, or both to be displayed.

When the datePickerMode attribute is set to calendar, the month and day can be selected using a calendar-style view while the year can be selected separately using a list.

Following is layout file.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="5dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <DatePicker
        android:id="@+id/dpDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:datePickerMode="spinner"
        android:calendarViewShown="false"
        />

    <Button
        android:id="@+id/btnGet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get date"
        android:onClick="getDate"/>

</LinearLayout>

Following is MainActivity.java file.

public class MainActivity extends AppCompatActivity {
    DatePicker dpDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dpDate = (DatePicker)findViewById(R.id.dpDate);
        // init
        // dpDate.init(2002, 10, 27, null);
    }

    public void getDate(View v) {
        StringBuilder builder=new StringBuilder();
        builder.append("Current Date: ");
        builder.append((dpDate.getMonth() + 1)+"/");//month is 0 based
        builder.append(dpDate.getDayOfMonth()+"/");
        builder.append(dpDate.getYear());
        Toast.makeText(this, builder.toString(), Toast.LENGTH_SHORT).show();
    }
}

Result

android_date_picker.png

TimePicker widget

Android TimePicker provides a widget for selecting the time of day, in either 24-hour or AM/PM mode. You cannot select time by seconds.

timePickerMode attribute defines the look of the widget. It could be either clock or spinner.

In order to get the time selected by the user on the screen, you will use getCurrentHour() and getCurrentMinute() method of the TimePicker class.

Following is layout file.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="5dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TimePicker
        android:id="@+id/tpTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:timePickerMode="spinner"
        />
</LinearLayout>

Following is MainActivity.java file.

public class MainActivity extends AppCompatActivity {
    TimePicker tpTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tpTime = (TimePicker)findViewById(R.id.tpTime);

        // set the time picker mode to 24 hour view
        tpTime.setIs24HourView(true);

        // set a time changed listener to time picker
        tpTime.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker timePicker, int i, int i1) {
                String time = "Current time: " + timePicker.getCurrentHour() + " : " + timePicker.getCurrentMinute();
                Toast.makeText(getApplicationContext(), time, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Result

android_time_picker.png

TimePickerDialog

Android TimePickerDialog allows you to select the time of day, in either 24-hour or AM/PM mode in your custom user interface. A dialog that prompts the user for the time of day using a TimePicker.

To show a TimePickerDialog we need to define a fragment class (named TimePickerDialog) which extends the DialogFragment class (available from API 11) and returns a TimePickerDialog from its onCreateDialog() method.

TimePickerDialog class have onTimeSetListener() callback method. This callback methods are invoked when the user is done with filling the time.

The TimePickerDialog class consists of a 5 argument constructor with the parameters listed below.

  • Context. It requires the application context.
  • onTimeSet() is callback function which invoked when the user sets the time with the following parameters:

    • int hourOfDay. It will be store the current selected hour of the day from the dialog.
    • int minute. It will be store the current selected minute from the dialog.
  • int mHours. It shows the the current hour that’s visible when the dialog pops up.

  • int mMinute. It shows the the current minute that’s visible when the dialog pops up.
  • boolean false. If its set to false it will show the time in 24 hour format else not.

Get TimePickerDialog by click on Button.

We will display TimePickerDialog dialog on click Button and display date on TextView.

Following is layout file.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="5dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnTime"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get time"
        android:onClick="getTime"/>

    <TextView
        android:id="@+id/tvTime"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18dp"/>
</LinearLayout>

Following is MainActivity.java file.

public class MainActivity extends AppCompatActivity {
    TextView tvTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvTime = (TextView) findViewById(R.id.tvTime);
    }

    public void getTime(View v) {
        DialogFragment dlg = new TimePickerFragment();
        dlg.show(getSupportFragmentManager(), "TimePicker");
    }
}

Following is TimePickerDialog.java file.

public class TimePickerFragment extends DialogFragment
    implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){
        // initialize a new Calendar instance
        final Calendar c = Calendar.getInstance();
        // get the current hour of day from calendar
        int hourOfDay = c.get(Calendar.HOUR_OF_DAY);
        // get the current minute from calendar
        int minute = c.get(Calendar.MINUTE);

        // boolean is24HourView = DateFormat.is24HourFormat(getActivity());
        // initialize a new time picker dialog
        TimePickerDialog timePickerDialog = new TimePickerDialog(
                getActivity(), // Context
                this, // Listener
                hourOfDay, // hourOfDay
                minute, // Minute
                true // is24HourView
        );

        // return the newly created time picker dialog
        return timePickerDialog;
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute){
        // get the TextView reference from activity
        TextView tv = (TextView) getActivity().findViewById(R.id.tvTime);

        // do something with selected time
        tv.setText("" + hourOfDay + ":" + minute);
    }
}

Result

android_time_picker_dialog1.png

Get TimePicker dialog by click on EditText.

We will display TimePickerDialog dialog on click EditText and display date on TextView.

Following is layout file.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:padding="5dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tvTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Time: "
        android:textSize="18dp"/>

    <EditText
        android:id="@+id/etTime"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="20:00"
        android:layout_weight="1"
        android:inputType="none"
        android:focusable="false"/>
</LinearLayout>

Following is MainActivity.java file.

public class MainActivity extends AppCompatActivity {
    EditText etTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etTime = (EditText) findViewById(R.id.etTime);

        etTime.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Calendar mcurrentTime = Calendar.getInstance();
                int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
                int minute = mcurrentTime.get(Calendar.MINUTE);

                TimePickerDialog dlg;
                dlg = new TimePickerDialog(SecondActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                        etTime.setText(selectedHour + ":" + selectedMinute);
                    }
                }, hour, minute, true);
                dlg.setTitle("Select Time");
                dlg.show();
            }
        });
    }
}

DatePickerDialog

Android DatePickerDialog allows you to select the date consisting of day, month and year in your custom user interface. It's a simple dialog containing an DatePicker.

To show a DatePickerDialog we need to define a fragment class (named DatePickerFragment) which extends the DialogFragment class (available from API 11) and returns a DatePickerDialog from its onCreateDialog() method.

DatePickerDialog class have onDateSetListener() callback method. This callback methods are invoked when the user is done with filling the date.

The DatePickerDialog class consists of a 5 argument constructor with the parameters listed below.

  • Context. It requires the application context.
  • onDateSet() is a callback function which invoked when the user sets the date with the following parameters

    • int year. It will be store the current selected year from the dialog.
    • int monthOfYear. It will be store the current selected month from the dialog.
    • int dayOfMonth. It will be store the current selected day from the dialog.
  • int mYear. It shows the the current year that’s visible when the dialog pops up.

  • int mMonth. It shows the the current month that’s visible when the dialog pops up.
  • int mDay. It shows the the current day that’s visible when the dialog pops up.

We will display DatePickerDialog dialog on click Button and display date on TextView.

Following is layout file.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="5dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnDate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get date"
        android:onClick="getDate"/>

    <TextView
        android:id="@+id/tvDate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18dp"/>
</LinearLayout>

To display DatePickerDialog, we will create a DatePickerFragment class that extends DialogFragment. Define the onCreateDialog() method to return an instance of DatePickerDialog.

public class DatePickerFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        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);

        return new DatePickerDialog(getActivity(),
                    (DatePickerDialog.OnDateSetListener)
                            getActivity(), year, month, day);
     }
}

We need to implement DatePickerDialog.OnDateSetListener interface to receive a callback when the user sets the date. Add onDateSet() method to sets the date by user.

public class MainActivity extends AppCompatActivity
    implements DatePickerDialog.OnDateSetListener {

    TextView tvDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvDate = (TextView) findViewById(R.id.tvDate);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
        Calendar cal = new GregorianCalendar(year, month, day);
        final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
        Log.d("VVV", dateFormat.format(cal.getTime()));
        tvDate.setText(dateFormat.format(cal.getTime()));
    }

    public void getDate(View v) {
        DatePickerFragment fragment = new DatePickerFragment();
        fragment.show(getSupportFragmentManager(), "Date dialog");
    }
}

Result

android_date_picker_dialog1.png

If you want to change color in DatePickerDialog use following approach. First, define new style for DatePickerDialog in styles.xml.

<resources>
    ...
    <style name="DatePicker" parent="Theme.AppCompat.Light.Dialog">
        <item name="colorAccent">#5C9BE5</item>
    </style>
</resources>

Second, add style ID to the constructor of DatePickerDialog.

return new DatePickerDialog(getActivity(), R.style.DatePicker,
        (DatePickerDialog.OnDateSetListener)
                getActivity(), year, month, day);

We can also change theme of DatePickerDialog by passing themeResId.

int themeResId = 2;

return new DatePickerDialog(getActivity(), themeResId,
        (DatePickerDialog.OnDateSetListener)
                getActivity(), year, month, day);

Result

android_date_picker_dialog2.png

Other libs for Date/Time pick

  • SingleDateAndTimePicker. You can now select a date and a time with only one widget!
  • MaterialDateRangePicker. A material Date Range Picker.
  • MaterialDateTimePicker. Material DateTime Picker tries to offer you the date and time pickers as shown in the Material Design spec, with an easy themable API. The library uses the code from the Android frameworks as a base and tweaked it to be as close as possible to Material Design example.
comments powered by Disqus