Question

Please refer to the following image:

enter image description here

The text above says Thu, Oct 28, 1909...while the datepicker actually has the value 3rd jan, 1902. What is the mistake?

Here is my code:

@SuppressWarnings("deprecation")
public void setTheDate(View v){
    showDialog(DATE_DIALOG_ID);
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        // set date picker as current date
        return new DatePickerDialog(this, datePickerListener, 
                year, month,day);
    }
    return null;
}

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

    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        year = selectedYear;
        month = selectedMonth;
        day = selectedDay;
        System.out.println("date" + year + month + day);
    }
}; 

DATE_DIALOG_ID is a final constant, and i call the setTheDate() method on the click of a button.

What am i doing wrong?

Was it helpful?

Solution 2

Simply try this, similar to your code only but it is working for me.

Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            y = c.get(Calendar.YEAR);
            m = c.get(Calendar.MONTH);
            dy = c.get(Calendar.DAY_OF_MONTH);

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

                public void onDateSet(DatePicker view, int year,
                        int monthOfYear, int dayOfMonth) {
                    Log.d("err", "onselect");
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;


                }
            };

            DatePickerDialog d = new DatePickerDialog(getActivity(),
                    mDateSetListener, mYear, mMonth, mDay);
            d.show();

OTHER TIPS

You can use this code to retrieve value from the date picker. Add this code inside the onDateSet() method of OnDateSetListener()

 TimestampField field = (TimestampField) fieldpicker;
 Timestamp timestamp = field.getTimestamp();
 timestamp.setYear(year - 1900);
 timestamp.setMonth(monthOfYear);
 timestamp.setDate(dayOfMonth);
 field.setTimestamp(timestamp);

This will display date in the correct format

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top