Android Time and Date picker tutorial Android 04.05.2017

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

Following is a DatePicker example in Kotlin.

class MainActivity : AppCompatActivity() {

    private lateinit var calendar:Calendar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Initialize a new calendar instance
        calendar = Calendar.getInstance()

        // Get the Calendar current year, month and day of month
        val thisYear = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        // Initialize the date picker widget with system current date
        date_picker.init(
                thisYear,
                month,
                day,
                DatePicker.OnDateChangedListener {view, year, monthOfYear, dayOfMonth ->
                    // Display the date picker selected date on text view
                    text_view.text = "Date Changed : ${formatDate(year,monthOfYear,dayOfMonth)}"
            }
        )


        // Set a click listener for set date button widget
        button_set.setOnClickListener{
            // Update the date picker data by a random date
            val year = randomInRange(2000,2025)
            val month = randomInRange(0,11)
            val day = randomInRange(0,27)

            // Update the date picker with random date
            date_picker.updateDate(
                    year, // Year
                    month, // The month which is starting from zero.
                    day // Day of month
            )

            // Toast the new date
            Toast.makeText(
                    applicationContext,
                    "Set Date : ${formatDate(year,month,day)}",
                    Toast.LENGTH_SHORT).show()

        }


        // Set a click listener for get date button widget
        button_get.setOnClickListener{
            // Get the date picker widget selected date
            val selectedDate = formatDate(date_picker.year,date_picker.month,date_picker.dayOfMonth)
            // Display the date picker selected formatted date
            text_view.text = "Selected Date : $selectedDate"
        }
    }

    // Custom method to format date
    private fun formatDate(year:Int, month:Int, day:Int):String{
        // Create a Date variable/object with user chosen date
        calendar.set(year, month, day, 0, 0, 0)
        val chosenDate = calendar.time

        // Format the date picker selected date
        val df = DateFormat.getDateInstance(DateFormat.MEDIUM)
        return df.format(chosenDate)
    }

    // Custom method to get a random number from the provided range
    private fun randomInRange(min:Int, max:Int):Int{
        // Define a new Random class
        val r = Random()

        // Get the next random number within range
        // Including both minimum and maximum number
        return r.nextInt((max - min) + 1) + min;
    }
}

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

Following is a TimePicker example in Kotlin.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Set a time change listener for time picker widget
        time_picker.setOnTimeChangedListener{
            view,hourOfDay,minute->
            text_view.text = "Time(HH:MM) ${getHourAMPM(hourOfDay)} " +
                    ": $minute ${getAMPM(hourOfDay)}"
        }
    }

    // Custom method to get time picker current time as string
    private fun getPickerTime(timePicker: TimePicker):String{
        val hour = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            timePicker.hour
        } else {
            timePicker.currentHour
        }

        val minute = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            timePicker.minute
        }else{
            timePicker.currentMinute
        }

       return "${getHourAMPM(hour)} : $minute ${getAMPM(hour)}"
    }

    // Custom method to set time picker time
    private fun setPickerTime(timePicker: TimePicker){
        // Get random time
        val hour = randomInRange(0,23)
        val minute = randomInRange(0,59)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            timePicker.hour = hour
            timePicker.minute = minute
        }else{
            timePicker.currentHour = hour
            timePicker.currentMinute = minute
        }
    }

    // Custom method to get AM PM value from provided hour
    private fun getAMPM(hour:Int):String{
        return if(hour>11)"PM" else "AM"
    }


    // Custom method to get hour for AM PM time format
    private fun getHourAMPM(hour:Int):Int{
        // Return the hour value for AM PM time format
        var modifiedHour = if (hour>11)hour-12 else hour
        if (modifiedHour == 0){modifiedHour = 12}
        return modifiedHour
    }

    // Custom method to get a random number from the provided range
    private fun randomInRange(min:Int, max:Int):Int{
        //define a new Random class
        val r = Random()

        //get the next random number within range
        // Including both minimum and maximum number
        return r.nextInt((max - min) + 1) + min;
    }
}

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();
            }
        });
    }
}

Following is a TimePickerDialog example in Kotlin.

Following is MainActivity.kt.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Set a click listener for button widget
        button.setOnClickListener{
            // Initialize a new TimePickerFragment
            val newFragment = TimePickerFragment()
            // Show the time picker dialog
            newFragment.supportFragmentManager(fragmentManager, "Time Picker")
        }
    }
}

Following is TimePickerFragment.kt.

class TimePickerFragment : DialogFragment(), TimePickerDialog.OnTimeSetListener {
    private lateinit var calendar:Calendar

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        // Initialize a Calendar instance
        calendar = Calendar.getInstance()

        // Get the system current hour and minute
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)

        // Create a TimePickerDialog with system current time
        return TimePickerDialog(
                activity, // Context
                android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth, // Theme
                this, // TimePickerDialog.OnTimeSetListener
                hour, // Hour of day
                minute, // Minute
                false // Is 24 hour view
        )
    }

    override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
        // Do something with the returned time
        val tv:TextView = activity.findViewById(R.id.text_view) as TextView
        tv.text = "Hour : Minute\n${getHourAMPM(hourOfDay)}:$minute ${getAMPM(hourOfDay)}"
    }

    // When user cancel the time picker dialog
    override fun onCancel(dialog: DialogInterface?) {
        Toast.makeText(activity,"Picker Canceled.",Toast.LENGTH_SHORT).show()
        super.onCancel(dialog)
    }

    // Custom method to get AM PM value from provided hour
    private fun getAMPM(hour:Int):String{
        return if(hour>11)"PM" else "AM"
    }

    // Custom method to get hour for AM PM time format
    private fun getHourAMPM(hour:Int):Int{
        // Return the hour value for AM PM time format
        var modifiedHour = if (hour>11)hour-12 else hour
        if (modifiedHour == 0){modifiedHour = 12}
        return modifiedHour
    }
}

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

Following is a DatePickerDialog example in Kotlin.

Following is MainActivity.kt.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Set a click listener for button widget
        button.setOnClickListener{
            // Initialize a new DatePickerFragment
            val newFragment = DatePickerFragment()
            // Show the date picker dialog
            newFragment.show(supportFragmentManager, "Date Picker")
        }
    }
}

Following is DatePickerFragment.kt.

class DatePickerFragment : DialogFragment(), DatePickerDialog.OnDateSetListener {

    private lateinit var calendar:Calendar

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        // Initialize a calendar instance
        calendar = Calendar.getInstance()

        // Get the system current date
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        // Initialize a new date picker dialog and return it
        return DatePickerDialog(
                activity, // Context
                // Put 0 to system default theme or remove this parameter
                android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth, // Theme
                this, // DatePickerDialog.OnDateSetListener
                year, // Year
                month, // Month of year
                day // Day of month
        )
    }


    // When date set and press ok button in date picker dialog
    override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
        Toast.makeText(
                activity,
                "Date Set : ${formatDate(year,month,day)}"
                ,Toast.LENGTH_SHORT
        ).show()

        // Display the selected date in text view
        activity?.findViewById<TextView>(R.id.text_view)?.text = formatDate(year,month,day)
    }


    // Custom method to format date
    private fun formatDate(year:Int, month:Int, day:Int):String{
        // Create a Date variable/object with user chosen date
        calendar.set(year, month, day, 0, 0, 0)
        val chosenDate = calendar.time

        // Format the date picker selected date
        val df = DateFormat.getDateInstance(DateFormat.MEDIUM)
        return df.format(chosenDate)
    }
}

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.
  • datepicker-timeline. An infinite scrolling timeline to pick a date.