one month ahead of the date on datepicker shows up on Toast message

I’m sorry for my poor English.

what I wanted to do was to make a message with the date which was chosen on DatePicker.

but what I see is a message with one month ahead of the date which was selected in the datepicker. for example, when I select 2021-04-15, the date on the Toast message is 2021-03-15

what did I do wrong?

”’

~
public void datepicker_dialog(View view){
    DialogFragment newFragment =  new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "DatePciker");
}
~



package com.song.androidprogramingbasic;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.Toast;
import androidx.fragment.app.DialogFragment;
import java.util.Calendar;

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
        Toast.makeText(getContext(), ""+year+"년 "+month+"월 "+day+"일", Toast.LENGTH_LONG).show();
    }
}

”’

Answer

The month value is based on 0. That means January is First month but its value is 0 in DatePicker. That means you need to add +1 to your month value to get the index of month according to real world standards.

int myMonth = month+1;
Toast.makeText(getContext(), ""+year+"년 "+myMonth+"월 "+day+"일", Toast.LENGTH_LONG).show();

Here is the official documentation.

A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.