I have an android app that requires user's date of birth and the data type is LocalDate because the backend uses it to calculate the age of that user and assign how much he/she will have to pay for the registration depending on the age. I have a button that when click, it will pop up a calendar dialog for the user to select the date of birth and display the date selected on the button as a text.The text on the button which is the selected date of birth will be read and stored as a string so that it can be used as the parameter for the date of birth. The button is working correctly but I'm having issue in the formatting because I want to format the string into a LocalDate. I'm getting this error that says Text '2000-10-23' could not be parsed at index 4. I don't know what I did wrong.
Here is the button in the XML
<Button
android:id="@+id/btn_date_of_birth"
style="@style/Base.Widget.AppCompat.Spinner.Underlined"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="select here"
android:theme="@style/EditText.Grey"
android:textAppearance="@style/TextAppearance.AppCompat.Medium"
android:textColor="@color/grey_40" />
Here is how I set the calendar and did the formatting
private void setDate(){
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
android.app.DatePickerDialog dialog = new DatePickerDialog(
PatientRegistrationActivity.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year,month,day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month = month + 1;
String date = year + "-" + month + "-" + day;
btnDateOfBirth.setText(date);
}
};
}
I now call the setDate method when the button is click
btnDateOfBirth.setOnClickListener(view -> {
setDate();
});
Now I want to format the date of birth displayed on the button and pass it to the date of birth which is of type LocalDate
String dateTime = btnDateOfBirth.getText().toString();
userDto.setDateOfBirth(LocalDate.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
But this is giving me an error that says Text '2000-10-23' could not be parsed at index 4.
Please how can I resolve this issue, I really need help