Android DatePicker TimePicker Example

DatePicker and TimePicker are all extends android.widget.FrameLayout. They are used to display date and time selection widget in android application. They can be used in either spinner mode or calendar mode ( date picker), clock mode ( time picker ). You can control their appearance with their properties.

1. DatePicker Properties.

  1. datePickerMode : Value can be spinner or calendar. If set to calendar, it will display a calendar which let you choose date. If set to spinner, it will display a spinner to let you choose date.
    DatePicker Calendar Mode
    datepicker calendar mode new
    DatePicker Spinner Mode
    datepicker spinner mode
  2. calendarViewShown : This is a boolean value, only take effect when datePickerMode  is spinner. If set to true, it will display a claendar.
  3. spinnersShown : This is a  boolean value also, only take effect when  datePickerMode  is spinner. If set to true, it will display a spinner.
  4. If both above two properties set to true of false, it will show both a spinner besides a calendar.
  5. minDate : Set the optional minimum date in mm/dd/yyy format.
  6. maxDate : Set the maximum date to select, format is mm/dd/yyyy.
  7. startYear : Set optional start year.
  8. endYear : Set optional end year.

Beside above properties, you can click here to see all DatePicker properties.

Please Note : DatePicker’s init(int year, int month, int day, OnDateChangedListener onDateChangedListener)  method is a very important method. This method can be used to initialize the DatePicker displayed year, month and day. And the onDateChangedListener object will listen to the user change date event. When user choose another date, the listener’s onDateChanged method will be invoked.

2. TimePicker Properties.

  1. timePickerMode : Value can be spinner or clock. When set it’ value to clock, it will display a clock. When set is’s value to spinner will display a spinner.
    TimePicker Clock Mode
    timepicker clock mode
    TimePicker Spinner Mode
    timepicker spinner mode
  2. headerBackground : This is a Color or Drawable resource id which can be set to TimePicker’s header background.
  3. is24HourView() : Check whether it is 24 hour time system.
  4. setIs24HourView(boolean 24HourView) : Set if use 24 hour time system.
  5. getHour() : Get current hour integer value.
  6. getMinute() : Get current minute integer value.
  7. setOnTimeChangedListener() : Set call back listener when time is changed.
READ :   Android Flexbox Layout Example

3. DatePicker TimePicker Examples.

android datepicker timepicker example

There is a DatePicker and a TimePicker in this example. When you change the date and time, the new date time will be shown in text view widget at bottom.

Please Note : You can not change timezone in DatePicker. You can only change timezone use java.util.Calendar class. And then get day info in that timezone.

activity_date_picker_time_picker.xml

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            tools:layout_editor_absoluteY="8dp"
            tools:layout_editor_absoluteX="8dp">

            <DatePicker
                android:id="@+id/datePickerExample"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:calendarViewShown="false"
                android:spinnersShown="true"
                android:startYear="2000"
                android:endYear="2100"
                android:maxDate="12/31/2100"
                android:minDate="01/01/2000"
                android:datePickerMode="spinner" />

            <TimePicker
                android:id="@+id/timePickerExample"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:timePickerMode="clock"
                android:headerBackground="@color/colorBlue" />

            <TextView
                android:id="@+id/textViewShowDateTime"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="" />
        </LinearLayout>
</ScrollView>

DatePickerTimePickerActivity.java

package com.dev2qa.example;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.Calendar;
import java.util.TimeZone;

public class DatePickerTimePickerActivity extends AppCompatActivity {

    private int year;
    private int month;
    private int day;
    private int hour;
    private int minute;
    private int seconds;


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

        // Get current calendar date and time.
        Calendar currCalendar = Calendar.getInstance();

        // Set the timezone which you want to display time.
        currCalendar.setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong"));

        year = currCalendar.get(Calendar.YEAR);
        month = currCalendar.get(Calendar.MONTH);
        day = currCalendar.get(Calendar.DAY_OF_MONTH);
        hour = currCalendar.get(Calendar.HOUR_OF_DAY);
        minute = currCalendar.get(Calendar.MINUTE);
        seconds = currCalendar.get(Calendar.SECOND);

        showUserSelectDateTime();

        // Get date picker object.
        DatePicker datePicker = (DatePicker)findViewById(R.id.datePickerExample);
        datePicker.init(year - 1, month  + 1, day + 5, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker datePicker, int year, int month, int day) {
                DatePickerTimePickerActivity.this.year = year;
                DatePickerTimePickerActivity.this.month = month;
                DatePickerTimePickerActivity.this.day = day;

                showUserSelectDateTime();
            }
        });

        // Get time picker object.
        TimePicker timePicker = (TimePicker)findViewById(R.id.timePickerExample);
        timePicker.setHour(this.hour);
        timePicker.setMinute(this.minute);

        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
                DatePickerTimePickerActivity.this.hour = hour;
                DatePickerTimePickerActivity.this.minute = minute;

                showUserSelectDateTime();
            }
        });

    }

    /* Show user selected date time in bottom text vew area. */
    private void showUserSelectDateTime()
    {
        // Get TextView object which is used to show user pick date and time.
        TextView textView = (TextView)findViewById(R.id.textViewShowDateTime);

        StringBuffer strBuffer = new StringBuffer();
        strBuffer.append("You selected date time : ");
        strBuffer.append(this.year);
        strBuffer.append("-");
        strBuffer.append(this.month+1);
        strBuffer.append("-");
        strBuffer.append(this.day);
        strBuffer.append(" ");
        strBuffer.append(this.hour);
        strBuffer.append(":");
        strBuffer.append(this.minute);
        strBuffer.append(":");
        strBuffer.append(this.seconds);

        textView.setText(strBuffer.toString());
        textView.setTextColor(Color.BLUE);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(20);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.