Android TimePicker and DatePicker Examples

In this tutorial, we are going to explore with android TimePicker and DatePicker. This is a beginner’s android tutorial but the concept explained in this tutorial will come handy when you are developing android application that requires user to input time or date using android time and date dialog picker.

If you are interested in letting the default time to current date so that users will not select any date that is below today, I will suggest in read my tutorial on how to set android datepicker to start from today’s date

We are going to create two android applications for the TimePicker and DatePicker. We will start with android TimePicker then to Datepicker but the apps will follow the same concept.

Before we dive into more details, it is important for us to understand what we are planning to achieve. Below is the screen-shot of the application we will be creating.

android datepicker

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidTimePicker

Package: com.inducesmile.androidtimepicker

Select Blank Activity

Name your activity : MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

 

Strings.xml

We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

<string name="app_name">Android TimePicker</string>
<resources>
    <string name="app_name">Android TimePicker</string>
    <string name="select_time">Select from time picker</string>
    <string name="not_text"> </string>
</resources>


Colors.xml

Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorBlack">#000000</color>
    <color name="colorDivider">#B6B6B6</color>
</resources>


activity_main.xml

In the main layout of the app, we are going to add a Button and TextView controls. When the button is clicked, it will open a TimePicker dialog that will enable the user to select a time. The selected time will be displayed on the TextView control.

Open the layout file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.androidtimepicker.MainActivity">
    <Button
        android:id="@+id/select_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="@string/select_time"
        android:padding="16dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"/>
    <TextView
        android:id="@+id/selected_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/select_time"
        android:textStyle="bold"
        android:layout_marginTop="80dp"
        android:text="@string/not_text" />
</RelativeLayout>


MainActivity.java

In the MainActivity, we are going to obtain the reference to the View controls. The next thing is to create an inner Fragment class that will extends the DialogFragment and the class will implement TimePickerDialog.OnTimeSetListener.

In the button click event method, the object of the TimePickerFragment class will be created and the show() method of the object is called. It takes the FragmentManager and a string unique identifier as parameters.

Open the MainActivity.java file and add the code below to the class.

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
    protected static TextView displayCurrentTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        displayCurrentTime = (TextView)findViewById(R.id.selected_time);
        Button displayTimeButton = (Button)findViewById(R.id.select_time);
        assert displayTimeButton != null;
        displayTimeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePicker mTimePicker = new TimePicker();
                mTimePicker.show(getFragmentManager(), "Select time");
            }
        });
    }
    public static class TimePicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);
            return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
        }
        @Override
        public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
            displayCurrentTime.setText("Selected Time: " + String.valueOf(hourOfDay) + " : " + String.valueOf(minute));
        }
    }
}


Android DatePicker Example

In this example, we are going to create a new project like before. Follow the steps above and create a new android project. We will name this new project AndroidDatePicker.

Once the project is created, we will copy the same content of the previous layout file and add to the layout file.

 

activity_main.xml

Open the activity_main layout file and add the code below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.androiddatepicker.MainActivity">
    <Button
        android:id="@+id/select_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="@string/select_time"
        android:padding="16dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"/>
    <TextView
        android:id="@+id/selected_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/select_time"
        android:textStyle="bold"
        android:layout_marginTop="80dp"
        android:text="@string/no_text" />
</RelativeLayout>


MainActivity.java

Open the MainActivity.java file and add the code below.

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
    protected static TextView displayCurrentTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        displayCurrentTime = (TextView)findViewById(R.id.selected_time);
        Button displayTimeButton = (Button)findViewById(R.id.select_time);
        assert displayTimeButton != null;
        displayTimeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerFragment mDatePicker = new DatePickerFragment();
                mDatePicker.show(getFragmentManager(), "Select date");
            }
        });
    }
    public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
        @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(), this, year, month, day);
        }
        public void onDateSet(DatePicker view, int year, int month, int day) {
            displayCurrentTime.setText("Selected date: " + String.valueOf(year) + " - " + String.valueOf(month) + " - " + String.valueOf(day));
        }
    }
}

This simple code snippets illustrate how to work with android TimePicker and DatePicker.

This brings us to the end of this tutorial. I hope that you have learn something. Run your app as see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

 

 

Remember to subscribe with your email address so that you will be among the first to receive my new android blog post once it is published.

Please if you love this tutorial, kindly download my android app – Complete Mathematics – in Google Play Store and let me know what you think about it. 

OTHER INTERESTING POSTS:

Add a Comment