Casting and getting values from date picker and time picker in android

90,391

Solution 1

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

Solution 2

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

Solution 3

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

}

Solution 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.

Solution 5

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.

Share:
90,391

Related videos on Youtube

Rahul Kalidindi
Author by

Rahul Kalidindi

Solutions Architect and Dev Android iOS Mobile Apps Chatbots

Updated on July 09, 2022

Comments

  • Rahul Kalidindi
    Rahul Kalidindi almost 2 years

    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???

  • Rahul Kalidindi
    Rahul Kalidindi about 14 years
    Can u plz provide an example??? i am getting an error while initializing the date and time objects
  • Paresh Mayani
    Paresh Mayani over 13 years
    @Jin Thank you Jin !! Found Helpful
  • espinchi
    espinchi about 10 years
    And, for those using Joda, use new DateTime(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), 0, 0)
  • Matt Quigley
    Matt Quigley about 10 years
    Beware, this will actually set the time of the returned Date to the current time, instead of midnight.
  • Matt Quigley
    Matt Quigley about 10 years
    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()).
  • naXa stands with Ukraine
    naXa stands with Ukraine over 9 years
    Nice method. But could you add TimePicker related code to it? Question is about DatePicker + TimePicker.
  • praxmon
    praxmon about 9 years
    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?
  • Guerneen4
    Guerneen4 about 9 years
    This, along withSimpleDateFormat which inherits from DateFormat are definitely the best and cleanest way IMHO
  • MojioMS
    MojioMS almost 8 years
    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.