如何从DatePicker获取日期“值”?

时间:2016-03-19 10:10:03

标签: android datepicker

我不知道如何从Datepicker获取日期值。

PickerDialog.java

package com.example.alecksjohanssen.newyorktimes;

/**
 * Created by AlecksJohanssen on 3/19/2016.
 */
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;

import java.util.Calendar;

public class PickerDialog extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)

    {   DateSettings dateSettings = new DateSettings(getActivity());
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int dayofmonth = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog;
        dialog = new DatePickerDialog(getActivity(),dateSettings,year,month,dayofmonth);
        return dialog;
    }
}
DateSetting.java
package com.example.alecksjohanssen.newyorktimes;

import android.app.DatePickerDialog;
import android.content.Context;
import android.widget.DatePicker;
import android.widget.Toast;

/**
 * Created by My name Is Hardline on 2/26/2016.
 */
public class DateSettings implements DatePickerDialog.OnDateSetListener {
    Context context;

    public DateSettings(Context context) {

        this.context = context;

    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthofyear,int dayofmonth) {
        Toast.makeText(context, "Selected date" + monthofyear + "/" + dayofmonth + "/" + year, Toast.LENGTH_LONG).show();
    }
}


  public void setDate() {
        PickerDialog pickerDialogs = new PickerDialog();
        pickerDialogs.show(getFragmentManager(), "date_picker");
    }

基本上就是它,它只显示选定的日期是。我仍在寻找如何提取日期数据,以便我可以把它放在我的开始日期:P。

2 个答案:

答案 0 :(得分:4)

您可以尝试这样

private void datePicker(){
            Calendar calendar = Calendar.getInstance();
            final  SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
            DatePickerDialog datePickerDialog = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                System.out.print(dateFormatter.format(newDate.getTime()));
            }

        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
}

答案 1 :(得分:0)

假设你有日历 mCalendar ,你想用它来启动日期选择器。

    dialog.getDatePicker().init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
        @Override
        public void onDateChanged(DatePicker datePicker, int i, int i2, int i3) {
            mCalendar.set(i, i2, i3);
        }
    });

然后获取选择日期

mCalendar.getTime()