Getting value from date picker issue

135 Views Asked by At

Im getting 3914-01-06 as an output when the datepicker selected value input is 2014-01-06

        int   day  = view.getDayOfMonth();
        int   month= view.getMonth();
        int   year = view.getYear();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formatedDate = sdf.format(new Date(year, month, day));
        Log.d("test", "" + formatedDate);//Here i'am retrieving 3914 instead 2014
2

There are 2 best solutions below

2
On

According to the documentation, Date()'s first argument is "the year minus 1900". That is why you get 3914 (=2014+1900). As the documentation also states, use Calendar or GregorianCalendar instead of Date.

1
On

you better work with calendar, here's a simple example :

   public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker
    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);

    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
    // Do something with the date chosen by the user
    int [] tabd=new int[3];
tabd[0]=day;
    tabd[1]=month+1;
    tabd[2]=year;
    Button b1=(Button)getActivity().findViewById(R.id.yourButton);
    String d=tabd[0]+"-"+tabd[1]+"-"+tabd[2];
// d is your string that contain the date now you can do whatever you want with it

}