27

I have a DatePicker and a TimePicker in my app. Can anyone tell me how to get the values of the date and time that are selected??? What i mean to say is, for EditText we can declare as

final EditText name = (EditText) this.findViewById(R.id.nametext);

and we can cast the data of it by using name.getText().toString().

So similarly how can we get the values of DatePicker and TimePicker to a String???

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
Rahul Kalidindi
  • 4,666
  • 14
  • 56
  • 92

9 Answers9

54

DatePicker has

getYear() 
getMonth() 
getDayOfMonth()

to make a Date object from a DatePicker you'd do new Date(datePicker.getYear() - 1900, datePicker.getMonth(), datePicker.getDayOfMonth());

Note that this constructor was deprecated in API level 1 - please refer to andrescanavesi's answer for a more appropriate way of creating a Date object.

TimePicker has

getCurrentHour()
getCurrentMinute()
Community
  • 1
  • 1
Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
  • Can u plz provide an example??? i am getting an error while initializing the date and time objects – Rahul Kalidindi Apr 07 '10 at 13:36
  • @Jin Thank you Jin !! Found Helpful – Paresh Mayani Nov 26 '10 at 11:04
  • 1
    And, for those using Joda, use `new DateTime(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), 0, 0)` – espinchi May 16 '14 at 18:55
  • 1
    Although this is a valid way to get the date, `datePicker.getCalendarView().getDate()` is probably a more accurate way of answering the given question; so you would use it as `new Date(datePicker.getCalendarView().getDate())`. – Matt Quigley May 26 '14 at 04:33
  • In case of the time picker, I get the hour and the minute in the form of an integer. So the hour is an `integer` and the minute is an `integer`. How do I get a date object to store the the time? – praxmon May 19 '15 at 14:01
28

I use this:

    /**
 * 
 * @param datePicker
 * @return a java.util.Date
 */
public static java.util.Date getDateFromDatePicket(DatePicker datePicker){
    int day = datePicker.getDayOfMonth();
    int month = datePicker.getMonth();
    int year =  datePicker.getYear();

    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, day);

    return calendar.getTime();
}
Andrés Canavesi
  • 2,164
  • 20
  • 21
  • Beware, this will actually set the time of the returned `Date` to the current time, instead of midnight. – Matt Quigley May 26 '14 at 04:32
  • 2
    Nice method. But could you add `TimePicker` related code to it? Question is about `DatePicker` + `TimePicker`. – naXa stands with Ukraine Dec 07 '14 at 21:17
  • Add this to include Hours and minutes from Timepicker calendar.set(Calendar.HOUR, expDate_hours); calendar.set(Calendar.MINUTE, expDate_mins); where expDate_hours and _mins are set in onTimeChanged in the OnTimeChangedListener of your timepicker. – MojioMS Jul 16 '16 at 10:40
5
date=(EditText)findViewById(R.id.date_of_birth_textfield);

date.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 showDialog(DATE_DIALOG_ID);

            }
        });


        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

updateDisplay();

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

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

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            System.out.println("calendar view shown.."+view.getCalendarViewShown());
        c.set(Calendar.YEAR, year);
              c.set(Calendar.MONTH, monthOfYear);
              c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
              mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);
                updateDisplay();
           // mMonth = monthOfYear;
           // mDay = dayOfMonth;

        }
    };

private void updateDisplay() {
        date.setText(
                new StringBuilder()
                // Month is 0 `based` so add 1


                .append(mYear).append("-").append(mMonth + 1).append("-").append(mDay).append(""));
        //date.setText(fmtDateAndTime.format(c.getTime()));

}
4

I'd suggest looking at the DateFormat class in android. Be careful to import the DateFormat mentioned in the android docs. After that, whatever formatting you want to achieve is really simple. For a basic Aug 12, 2012 you can do this.

DatePicker myDatePicker = (DatePicker) findViewById(R.id.mydatepicker);
String selectedDate = DateFormat.getDateInstance().format(myDatePicker.getCalendarView().getDate());

Look at the DateFormat class to get various other configurations.

Sojurn
  • 475
  • 6
  • 15
  • This, along with`SimpleDateFormat` which inherits from `DateFormat` are definitely the best and cleanest way IMHO – Guerneen4 May 28 '15 at 13:42
3

Combined all the answers and made a code snippet out of it.

Import datePicker on the top of your class:

import android.widget.DatePicker;

Inside your class declare the following variable:

private DatePicker dobPicker;

And here is the code to be done in button click event:

 dobPicker = (DatePicker)findViewById(R.id.dobPicker);
        Integer dobYear = dobPicker.getYear();
        Integer dobMonth = dobPicker.getMonth();
        Integer dobDate = dobPicker.getDayOfMonth();
        StringBuilder sb=new StringBuilder();
        sb.append(dobYear.toString()).append("-").append(dobMonth.toString()).append("-").append(dobDate.toString()).append(" 00:00:00");
        String dobStr=sb.toString();

Where in R.id.dobPicker, dobPicker is your datePicker in the layout xml file. This gives you a string at the end, which could be stored or sent to the server.

happyhardik
  • 24,987
  • 7
  • 47
  • 60
2

getDateTimeFromPickers()

Simple Method for Getting Date and Time from a DatePicker and a TimePicker

Caveat: it uses JodaTime's DateTime as the return. You can modify it to use whatever you like.

 // Gets the Date and Time from a DatePicker and TimePicker and return a JodaTime DateTime from them, in current timezone.
 //
 private DateTime getDateTimeFromPickers( int DatePickerId, int TimePickerId ) {
     DatePicker dp = (DatePicker) findViewById(DatePickerId);
     TimePicker tp = (TimePicker) findViewById(TimePickerId);

     String year    = Integer.toString(dp.getYear()) ;
     String month   = StringUtils.leftPad( Integer.toString(dp.getMonth() + 1), 2, "0" );
     String day     = StringUtils.leftPad( Integer.toString(dp.getDayOfMonth()), 2, "0" );
     String hour    = StringUtils.leftPad( Integer.toString(tp.getCurrentHour()), 2, "0" );
     String minutes = StringUtils.leftPad( Integer.toString(tp.getCurrentMinute()), 2, "0" );

     String dateTime = year + "-" + month + "-" + day + "T" + hour + ":" + minutes + ":00.000";

     return DateTime.parse(dateTime);
 }

Hope that helps.

JP

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
2

I would do it as:

    Calendar calendar = Calendar.getInstance();
    calendar.set(dp.getYear(), dp.getMonth(), dp.getDayOfMonth(), Tp.getCurrentHour(), Tp.getCurrentMinute());
    DateFormat gmtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    TimeZone gmtTime = TimeZone.getTimeZone("GMT");
    gmtFormat.setTimeZone(gmtTime);
    String mydate = ""+ gmtFormat.format(calendar.getTime());

p.s dp and tp are date pickers and time picker in android.

Hassi
  • 120
  • 8
0
StringBuilder sb=new StringBuilder();
        sb.append(myYear).append("-").append(myMonth).append("-").append(myDay);
    String str=sb.toString();
    edittext.setText(str);
swathi
  • 673
  • 1
  • 5
  • 7
0

Try bellow with Format Ex: 24 December 2014.

            DatePicker datePicker = (DatePicker) findViewById(R.id.datepicker_inspection);
            SimpleDateFormat df = new SimpleDateFormat("dd MMMM yyyy");
            String inspectiondate = df.format(new Date(datePicker.getYear() - 1900, datePicker.getMonth(), datePicker.getDayOfMonth()));
Imran Athar
  • 469
  • 5
  • 8