从字符串在DatePickerDialog中设置日期

时间:2019-10-05 21:53:01

标签: java android

如何通过字符串(例如:02/10/19)在DatePicker中设置日期:

以下是代码:

  iqp_editDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new DatePickerDialog(ActivityClass.this, (DatePickerDialog.OnDateSetListener) date1, y, m, d).show();
        }
    });

 DatePickerDialog.OnDateSetListener date1 = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {      
        y = year;
        m = month;
        d = dayOfMonth;
        dateMonth = month + 1;
        dateYear = year;
    }
};

3 个答案:

答案 0 :(得分:1)

更新:误解了这个问题:

Calendar cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY,18);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.DATE,2);
cal.set(Calendar.MONTH,9); //Month -1

//Or to set it from a String:
String string = "02/10/19";
DateFormat format = new SimpleDateFormat("dd/MM/yy", Locale.getDefault());
Date date = format.parse(string);
cal.setTimeInMillis(date.getTime());

new DatePickerDialog(getContext(),date1, cal 
                                    .get(Calendar.YEAR), cal .get(Calendar.MONTH),
                                    cal .get(Calendar.DAY_OF_MONTH)).show();

答案 1 :(得分:0)

字符串是一个字符数组。这意味着您可以进行循环并为字符串的不同部分设置不同的日,月和年值。

String date = "02/19/19";
String year = "";
for(int i = 0; i < date.length; i++)
{
  month += date.charAt(i);
  ...
}

然后,您会告诉它遇到“ /”时何时从添加到逐月切换到逐年。

if(date.charAt(i) == '/')
{
  ...
}

如果需要将其转换为一个int,则在最后做

int month = Integer.parseInt("month");

抱歉,我必须去某个地方,所以我不能只为ya写代码,但我敢肯定,您可以从我给ya的东西中弄清楚。

答案 2 :(得分:0)

以下代码对我来说很好:

new DatePickerDialog(Activityclass.this, date1, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show();

DatePickerDialog.OnDateSetListener date1 = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        view.setMinDate(1559327400);
        y = year;
        m = month;
        d = dayOfMonth;
        dateMonth = month + 1;
        dateYear = year;
        iqp_editDate.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
        try {
            epoch = new java.text.SimpleDateFormat("MM/dd/yyyy").parse(m + "/" + dayOfMonth + "/" + year).getTime() / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
};