Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateFormat produce wrong year

Date picker

The above picture is the date picker, after I click OK, the result is shown below.

Text View

The code is as follow

public class DatePickerFragment extends DialogFragment
    implements DatePickerDialog.OnDateSetListener {

@Override
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
    Date date = new Date(year, month, day);
    Fragment fragment = getActivity().getFragmentManager().findFragmentByTag(ConvocationAddDialogFragment.class.getName());
    TextView textView = (TextView) fragment.getView().findViewById(R.id.open_registration_date);
    textView.setText(DateFormat.getDateInstance().format(date));
}
}

The expected value is 18 Jan 2016, why is it displaying 18 Jan 3916?

like image 642
Andrew Lam Avatar asked May 14 '26 21:05

Andrew Lam


1 Answers

As per Source code new Date(year, month, day);

public Date(int year, int month, int day) {
    GregorianCalendar cal = new GregorianCalendar(false);
    cal.set(1900 + year, month, day);
    milliseconds = cal.getTimeInMillis();
}

Here, Your year 2016 will get added to 1900 , which result into 3916.

Try,

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
Date date = calendar.getTime();
like image 178
Dhaval Patel Avatar answered May 17 '26 11:05

Dhaval Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!