TimePicker in Android Tutorial/Example

In this tutorial, I will show you how to implement TimePicker and TimePickerDialog in Android. TimePicker is a widget in Android which allows you to select a time in terms of hour and minutes. TimePickerDialog is a dialog which allows to select the time and provides the selected time in an override method.

layout file including text-view where selected time from time picker dialog is shown, a button on which click a Timepickerdialog will be shown and a time-picker widget.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.coderzpassion.timepicker.MainActivity">

    <TimePicker
        android:id="@+id/timepick"
        android:layout_alignParentTop="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TimePicker>

    <TextView
        android:id="@+id/settime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="dcdc"
        android:layout_above="@+id/bt_settime"
        android:layout_centerHorizontal="true"
        />

    <Button
        android:id="@+id/bt_settime"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:text="Set Time"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>

MainActivity.java 

package com.coderzpassion.timepicker;

import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    TextView settime;
    Button bt_settime;
    Calendar calendar;
    int hour,min;
    TimePicker picker;

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

        settime=(TextView)findViewById(R.id.settime);
        bt_settime=(Button)findViewById(R.id.bt_settime);
        bt_settime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openTimePickerDialog();
            }
        });

        picker=(TimePicker)findViewById(R.id.timepick);
        setCurrentTimeFirstTime();
        picker.setIs24HourView(false);
    }

    //function to set current time to textview
    private void setCurrentTimeFirstTime()
    {
        calendar=Calendar.getInstance();
         hour=calendar.get(Calendar.HOUR_OF_DAY);
         min=calendar.get(Calendar.MINUTE);
        settime.setText(updateTime(hour,min));
    }

    //function to show timepicker dialog
    private void openTimePickerDialog()
    {
        TimePickerDialog dialog=new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int hour, int min) {
                //set selected time to textview
                settime.setText(updateTime(hour,min));

            }
        },hour,min,false);

        dialog.show();
    }

    // function to get am and pm from time
    private String updateTime(int hours, int mins) {

        String timeSet = "";
        if (hours > 12) {
            hours -= 12;
            timeSet = "PM";
        } else if (hours == 0) {
            hours += 12;
            timeSet = "AM";
        } else if (hours == 12)
            timeSet = "PM";
        else
            timeSet = "AM";


        String minutes = "";
        if (mins < 10)
            minutes = "0" + mins;
        else
            minutes = String.valueOf(mins);

        // Append in a StringBuilder
        String aTime = new StringBuilder().append(hours).append(':')
                .append(minutes).append(" ").append(timeSet).toString();

        return aTime;
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzpassion.timepicker">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.coderzpassion.timepicker"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.android.support:appcompat-v7:25.4.0'
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}

Output

timepickerdialogexample    timepickerexample