如何在日期选择器android中获得正确的月份

时间:2017-01-17 10:04:49

标签: android calendar

这是我的代码:

self.bStop.clicked.connect(lambda: self.hide_layout(*buttons(self)))

我收到以下输出:int day = d.getDayOfMonth(); int month = d.getMonth() + 1; int year = d.getYear(); Calendar calendar = Calendar.getInstance(); calendar.set(year, month, day); SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd"); String strDate = format.format(calendar.getTime()); 但我应该2017-31-17

为了在2017-01-17中获得正确的月份,我应该更改哪些内容?

2 个答案:

答案 0 :(得分:1)

您可以使用datePicker,如下所示

   Calendar newCalendar = Calendar.getInstance();
    DatePickerDialog  fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {

    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        Calendar newDate = Calendar.getInstance();
        newDate.set(year, monthOfYear, dayOfMonth);
//set date format in your TextView
        fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
    }

},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
fromDatePickerDialog.show();

我希望它适合你。谢谢

答案 1 :(得分:0)

final Calendar c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);




                    DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                            new DatePickerDialog.OnDateSetListener() {

                                    @Override
                                    public void onDateSet(DatePicker view, int year,
                                                          int monthOfYear, int dayOfMonth)
                                    {
                                            dates = dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;
                                            txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

                                    }
                            }, mYear, mMonth, mDay);
                    datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());

                    datePickerDialog.show();