147

Is there any android widget that enable to pick the date and the time at the same time ? I already use the basic time picker and date picker.

But they are not that sexy and user friendly (I found). Do you know if a widget including both date and time exists?

Thanks a lot, Luc

Otziii
  • 2,304
  • 1
  • 25
  • 34
Luc
  • 16,604
  • 34
  • 121
  • 183
  • 1
    There is a Github library for date and time picker: [AndroidDateTimePicker](https://github.com/Fei-Sheng-Wu/AndroidDateTimePicker). –  Oct 12 '20 at 17:42

15 Answers15

90

Put both DatePicker and TimePicker in a layout XML.

date_time_picker.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:padding="8dp"
    android:layout_height="match_parent">

    <DatePicker
        android:id="@+id/date_picker"
        android:layout_width="match_parent"
        android:calendarViewShown="true"
        android:spinnersShown="false"
        android:layout_weight="4"
        android:layout_height="0dp" />

    <TimePicker
        android:id="@+id/time_picker"
        android:layout_weight="4"
        android:layout_width="match_parent"
        android:layout_height="0dp" />

    <Button
        android:id="@+id/date_time_set"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:text="Set"
        android:layout_height="0dp" />

</LinearLayout>

The code:

final View dialogView = View.inflate(activity, R.layout.date_time_picker, null);
final AlertDialog alertDialog = new AlertDialog.Builder(activity).create();

dialogView.findViewById(R.id.date_time_set).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

         DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.date_picker);
         TimePicker timePicker = (TimePicker) dialogView.findViewById(R.id.time_picker);

         Calendar calendar = new GregorianCalendar(datePicker.getYear(),
                            datePicker.getMonth(),
                            datePicker.getDayOfMonth(),
                            timePicker.getCurrentHour(),
                            timePicker.getCurrentMinute());

         time = calendar.getTimeInMillis();
         alertDialog.dismiss();
    }});
alertDialog.setView(dialogView);
alertDialog.show();
Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53
Oded Breiner
  • 28,523
  • 10
  • 105
  • 71
  • 2
    Brilliant example, thanks. One point... you probably want to have alertDialog.dismiss(); at the end of the onClick implementation. – Jonathan Sep 15 '14 at 17:16
  • Can't pick year in this example. – lostintranslation May 03 '15 at 02:20
  • Just one problem...when using in android L the date and time picker do not fit on the screen..so i put the linearLayout in a scrollView ...Now the problem is that when i try to change the time the layout scrolls because of the scrollView..Any solution to this – Dominic D'Souza Jul 10 '15 at 04:52
  • please help , it is not fit in landscape mode, how to fix it – Awadesh Oct 16 '15 at 12:23
  • @Awadesh , For landscape, you'll have to create another xml like: http://stackoverflow.com/a/4858052/710284 – Oded Breiner Oct 16 '15 at 12:24
  • it is working but when i switch from landscape mode to portrait or vice-versa it is not changing automatically – Awadesh Oct 16 '15 at 12:44
  • 1
    Android 6.0+ this layout looks ugly ;( https://static.pychat.org/photo/f1qRFo31_Screenshot_20170214-123713.png – deathangel908 Feb 14 '17 at 10:38
  • But they are overlapping each other, maybe if you used scrollview as a root layout it would be much better – Anas.J Jul 10 '19 at 14:29
81

Use this function it will enable you to pic date and time one by one then set it to global variable date. No library no XML.

Calendar date;
public void showDateTimePicker() {
   final Calendar currentDate = Calendar.getInstance();
   date = Calendar.getInstance();
   new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
       @Override
       public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            date.set(year, monthOfYear, dayOfMonth);
            new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    date.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    date.set(Calendar.MINUTE, minute);
                    Log.v(TAG, "The choosen one " + date.getTime());
                }
            }, currentDate.get(Calendar.HOUR_OF_DAY), currentDate.get(Calendar.MINUTE), false).show();
       }
   }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
}
Abhishek
  • 2,295
  • 24
  • 28
54

There is nothing built into Android that offers this.

EDIT: Andriod now offers built-in pickers. Check @Oded answer

M. Usman Khan
  • 3,689
  • 1
  • 59
  • 69
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 2
    I know this response is more than a year old, but I think this response should be updated. The DateSlider library referenced by Rabi all the way below seems to be perfect for this. – Stephan Branczyk Aug 07 '11 at 21:09
  • I agree this answer should be updated because that's an awesome widget. However the code pointed to by Rabi is already a bit outdated and contains some deprecated methods e.g. `showDialog`. Perhaps something more current will come along soon. – Eugene van der Merwe Jun 09 '12 at 20:32
  • 14
    Actually answer is correct and shouldn't be updated. Even if AndroidDateSlider exist, there is nothing built into Android that offers that feature. – Cristian Jun 16 '12 at 17:09
  • 4
    Am I the only one baffled at the fact that Google doesn't even support one of the most widely used controls in any business applications out there? – TtT23 Jan 05 '15 at 03:13
29

combined DatePicker and TimePicker in DialogFragment for Android

I created a library to do this. It also has customizable colors!

It's very simple to use.

First you create a listener:

private SlideDateTimeListener listener = new SlideDateTimeListener() {

    @Override
    public void onDateTimeSet(Date date)
    {
        // Do something with the date. This Date object contains
        // the date and time that the user has selected.
    }

    @Override
    public void onDateTimeCancel()
    {
        // Overriding onDateTimeCancel() is optional.
    }
};

Then you create and show the dialog:

new SlideDateTimePicker.Builder(getSupportFragmentManager())
    .setListener(listener)
    .setInitialDate(new Date())
    .build()
    .show();

I hope you find it useful.

Gene Bo
  • 11,284
  • 8
  • 90
  • 137
JDJ
  • 4,298
  • 3
  • 25
  • 44
  • really good one ! saved my time ! thanks ! However, i had to clone the code, because i think gradle dependency string is not valid ? – kuldeep Aug 20 '15 at 14:21
  • @k2ibegin the git page of project says to import the whole module or "clone the code", thats the point, he didn't publish his awesome date-time-picker in any repository. JDJ nice work man, great lib. – Ninja Coding Jul 07 '16 at 00:27
  • @JDJ sorry, but i haven't been able to add your library to my project, could you explain how ? – Sebastian Delgado Jul 08 '16 at 05:40
  • @Kuriel How can i add the library ? – Sebastian Delgado Jul 08 '16 at 15:22
  • 3
    **Step 1** download the whole project by clicking "Clone or download" and then "download ZIP" **Step 2** extract zip content, or just the ZIP\SlideDateTimePicker-master\ **slideDateTimePicker** folder and copy that folder to your **root** folder container of your existing project where you want to add the plugin. **Step 3** add the Dependency via Gradle with **compile project(':slideDateTimePicker')** OR with Android Studio: File > New > Import Project and select the extracted folder and configure project import normally accept and next and finish. – Ninja Coding Jul 08 '16 at 18:38
  • 2
    @JDJ we have a bug, on Lollipop or Marshmallow the native DatePicker and TimePicker is not shown, instead shows the pre-lollipop components. – Ninja Coding Jul 09 '16 at 01:26
  • @JDC I tried lots of things but could not change theme. How can we implement Material Design? – Mucahit Dec 22 '16 at 06:38
  • Error:(30, 0) Project with path ':slideDateTimePicker' could not be found in project ':app'. Open File – Ruchir Baronia Nov 05 '17 at 02:13
  • For adding the library manually, I found that **settings.gradle** needs to be updated with a reference to the lib, like so: `include ':app', .. ':slideDateTimePicker'` .. thanks to details in *"Method 1"* here : https://github.com/MagicMicky/FreemiumLibrary/wiki/Import-the-library-in-Android-Studio – Gene Bo Dec 21 '17 at 03:03
  • Please note I believe this library no longer works, and has been abandoned. https://github.com/jjobes/SlideDateTimePicker/issues/59 – Joshua Sep 24 '18 at 11:20
  • How do you customize the color of horizontal date and time divider? When you use the setIndicatorColor(), it only changes the color header, not date/time divider – Mehran Jun 27 '19 at 14:04
  • The original project has been forked and updated: https://github.com/yulmaso/SlideDateTimePicker – mike47 Nov 05 '21 at 18:46
21

Call the time picker dialog in the DatePicker update time method. It'll not be called at the same time but when you press DatePicker set button. The time picker dialog will open. The method is given below.

package com.android.date;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

public class datepicker extends Activity {

    private TextView mDateDisplay;
    private Button mPickDate;
    private int mYear;
    private int mMonth;
    private int mDay;
    private TextView mTimeDisplay;
    private Button mPickTime;

    private int mhour;
    private int mminute;

    static final int TIME_DIALOG_ID = 1;

    static final int DATE_DIALOG_ID = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mDateDisplay =(TextView)findViewById(R.id.date);
        mPickDate =(Button)findViewById(R.id.datepicker);
        mTimeDisplay = (TextView) findViewById(R.id.time);
        mPickTime = (Button) findViewById(R.id.timepicker);

        //Pick time's click event listener
        mPickTime.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        //PickDate's click event listener 
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mhour = c.get(Calendar.HOUR_OF_DAY);
        mminute = c.get(Calendar.MINUTE);
    }

    //-------------------------------------------update date---//    
    private void updateDate() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mDay).append("/")
                    .append(mMonth + 1).append("/")
                    .append(mYear).append(" "));
        showDialog(TIME_DIALOG_ID);
    }

      //-------------------------------------------update time---//    
    public void updatetime() {
        mTimeDisplay.setText(
                new StringBuilder()
                        .append(pad(mhour)).append(":")
                        .append(pad(mminute))); 
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);


    //Datepicker dialog generation  

    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDate();
            }
        };


     // Timepicker dialog generation
        private TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    mhour = hourOfDay;
                    mminute = minute;
                    updatetime();
                }
            };

        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this,
                            mDateSetListener,
                            mYear, mMonth, mDay);

            case TIME_DIALOG_ID:
                return new TimePickerDialog(this,
                        mTimeSetListener, mhour, mminute, false);

            }
            return null;
        }
}

the main.xml is given below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="@string/hello"/>

    <TextView android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>

    <Button
        android:id="@+id/timepicker"
        android:text="Change Time" 
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content"/>

    <TextView 
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>

    <Button android:id="@+id/datepicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="200dp"
        android:text="Change the date"/>

</LinearLayout>
Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
Jaydeep Khamar
  • 5,975
  • 3
  • 32
  • 30
15

I also wanted to combine a DatePicker and a TimePicker. So I create an API to handle both in one interface! :)

https://github.com/Kunzisoft/Android-SwitchDateTimePicker

enter image description here

You can also use SublimePicker

J-Jamet
  • 847
  • 8
  • 17
  • Very nice elegant solution. Works great. A few small details I ran into .. 1) The AM/PM label was getting truncated, so I had to set a smaller font size in style: `11sp` and remove the bold setting. 2) looks like `setDefaultDateTime(..)` must be called or you get a runtime exception .. so I call that with just `Calendar.getInstance().getTime()` as the parameter. Best github project for a date picker I have seen so far - thanks for sharing it – Gene Bo Dec 21 '17 at 03:48
13

The URLs you link to show how to pop up a dialog with a time picker and another dialog with a date picker. However you need to be aware that you can use those UI widgets directly in your own layout. You could build your own dialog that includes both a TimePicker and DatePicker in the same view, thus accomplishing what I think you are looking for.

In other words, instead of using TimePickerDialog and DatePickerDialog, just use the UI widgets TimePicker and DatePicker directly in your own dialog or activity.

Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80
Mark B
  • 183,023
  • 24
  • 297
  • 295
  • 1
    I agree @Jaydeep Khamar's solution is not what is asked for, those are opening two separate dialogs. It would be better to see basic sample code where this is already combined. – Eugene van der Merwe Jun 18 '12 at 05:48
9

I was facing the same problem in one of my projects and have decided to make a custom widget that has both the date and the time picker in one user-friendly dialog. You can get the source code along with an example at http://code.google.com/p/datetimepicker/. The code is licensed under Apache 2.0.

ptashek
  • 186
  • 2
  • 6
6

I forked, updated, refactored and mavenized the android-dateslider project. It is on Github now:

https://github.com/casidiablo/date-slider

Cristian
  • 198,401
  • 62
  • 356
  • 264
5

You can use one of DatePicker library wdullaer/MaterialDateTimePicker

  • First show DatePicker.

    private void showDatePicker() {
    Calendar now = Calendar.getInstance();
    DatePickerDialog dpd = DatePickerDialog.newInstance(
            HomeActivity.this,
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH)
    );
    dpd.show(getFragmentManager(), "Choose Date:");
    }
    
  • Then onDateSet callback store date & show TimePicker

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, monthOfYear, dayOfMonth);
    filter.setDate(cal.getTime());
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            showTimePicker();
        }
    },500);
    }
    
  • On onTimeSet callback store time

     @Override
     public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
    Calendar cal = Calendar.getInstance();
    if(filter.getDate()!=null)
        cal.setTime(filter.getDate());
    cal.set(Calendar.HOUR_OF_DAY,hourOfDay);
    cal.set(Calendar.MINUTE,minute);
    }
    
Khaled Lela
  • 7,831
  • 6
  • 45
  • 73
4

enter image description here

May be this tutorial link will help http://custom-android-dn.blogspot.com/2013/03/how-to-create-custom-date-time-picker.html

nghien_rbc
  • 133
  • 1
  • 12
3

I wrote up a little widget that allows you to pick both date and time.

DateTimeWidget

enter image description here

Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106
  • Hello. Sorry for the necro post, but is it possible to import your widget into my .xml layout file? – Tim Mar 11 '21 at 20:37
2

Another option is the android-wheel project that comes pretty close the the UIDatePicker dialog of iOS.

It provides a vertical slider to pick anything(including date and time). If you prefer horizontal slider, the DateSlider referenced by Rabi is better.

pellucide
  • 3,407
  • 2
  • 22
  • 25
  • Broken link. Here's a [fork of android-wheel](https://github.com/maarek/android-wheel). – jk7 Apr 17 '17 at 23:19
1

I have create a alert dialog which combine Date picker and Time picker. You can get code at https://github.com/nguyentoantuit/android Note: DateTimePicker is a library

  • 1
    Note that [link-only answers](http://meta.stackoverflow.com/tags/link-only-answers/info) are discouraged, SO answers should be the end-point of a search for a solution (vs. yet another stopover of references, which tend to get stale over time). Please consider adding a stand-alone synopsis here, keeping the link as a reference. – kleopatra Dec 12 '13 at 15:23
1

Here is a more compact version of Jaydeep's idea of showing one dialog after the other. I like this solution because it has no dependencies.

        Date value = new Date();
        final Calendar cal = Calendar.getInstance();
        cal.setTime(value);
        new DatePickerDialog(this,
            new DatePickerDialog.OnDateSetListener() {
                @Override public void onDateSet(DatePicker view, 
                        int y, int m, int d) {
                    cal.set(Calendar.YEAR, y);
                    cal.set(Calendar.MONTH, m);
                    cal.set(Calendar.DAY_OF_MONTH, d);

                    // now show the time picker
                    new TimePickerDialog(NoteEditor.this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override public void onTimeSet(TimePicker view, 
                                    int h, int min) {
                                cal.set(Calendar.HOUR_OF_DAY, h);
                                cal.set(Calendar.MINUTE, min);
                                value = cal.getTime();
                            }
                        }, cal.get(Calendar.HOUR_OF_DAY), 
                            cal.get(Calendar.MINUTE), true).show();
                 }
            }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
            cal.get(Calendar.DAY_OF_MONTH)).show();
Roger Keays
  • 3,117
  • 1
  • 31
  • 23