Set date of datepickerdialog from EditText

不羁的心 提交于 2019-12-06 09:56:52
tyczj

Using SimpleDateFormat you can convert the date in the edittext to milliseconds.

example:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy",Locale.US);

you will need to adjust the format based on how you are displaying it but after that just use the parse method from the DateFormat object

Date d = df.parse(dateString);

then create a Calendar object and set the date

Calendar calendar = Calendar.getInstance();
calendar.setDate(d);

Edit:

to send the text from the EditText you need to send the string in the bundle when you create the dialogfragment

example:

DialogFragment newFragment = new DatePickerFragment();
Bundle bundle = new Bundle();
bundle.putString("dateAsText",edit_datepurchased.getText().toString());
newFragment.setArguments(bundle); 
newFragment.show(getFragmentManager(), "datePicker");

then in your dialogfragment use getArguments() to get the bundle

Bundle bundle = getArguments();
String date = bundle.getString("dateAsText");

I hope it helps you:

public class DatePickerFragment extends DialogFragment
{
    private OnDateSetListener onDateSetListener;

    public DatePickerFragment() {}

    public void setOnDateSetListener(OnDateSetListener onDateSetListener) {
        this.onDateSetListener = 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(), onDateSetListener, year, month, day);
    }

}

"final Calendar c=Calendar.getInstance();" ,This code set "c" to current time,modify it to what time you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!