如何将两个不同的dateFormat字符串存储为两个变量

时间:2015-07-22 05:28:23

标签: java android datetime android-datepicker

我有一个EditText,点击事件我正在显示DatePicker对话框,并以" MMMM dd,yyyy" 格式显示选择日期,即1932年6月26日。 但我需要将不同格式的日期传递给服务器;我需要传递的格式是" 1932-06-26" 。以下是我的代码:

       {
    dateFormatter = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);        
                birthDate = (EditText) findViewById(R.id.birthday);
                birthDate.setInputType(InputType.TYPE_NULL);
                setDateTimeField();
    }

private void setDateTimeField() {
        birthDate.setOnClickListener(this);
        Calendar newCalendar = Calendar.getInstance();
        birthDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

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

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

为了以不同的格式存储日期,我遵循以下方法:

 birthDate = (EditText) findViewById(R.id.birthday);
        SimpleDateFormat formatDate = new SimpleDateFormat("dd MMM yyyy",Locale.US);
        String output = formatDate.format(birthDate.getText().toString());
        Log.d(TAG,"FORMATED DATE IS   ::::: " + output);

但是我得到了一个j ava.lang.IllegalArgumentException:Bad class:class java.lang.String 错误。

是否可以以一种格式显示日期并将日期存储为不同的格式?

3 个答案:

答案 0 :(得分:2)

首先,你必须将字符串解析为日期,然后你可以格式化它:

此代码应该有效:

birthDate = (EditText) findViewById(R.id.birthday);
SimpleDateFormat formatDate1 = new SimpleDateFormat("MMMM dd,yyyy",Locale.US);
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
String output = formatDate.format(formatDate1.parse(birthDate.getText().toString()));

答案 1 :(得分:1)

试试这个

    String tmpDate = "June 26, 1932" ;
    String parsedDate = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("MMMM dd, yyyy").parse(tmpDate));
    Log.d(TAG,"FORMATED DATE IS   ::::: " + parsedDate);

答案 2 :(得分:1)

以下是我尝试过的最终答案,并且工作得很好。我创建了一个函数并返回了我想要的最终输出。

private String formatDate() {
        birthDate = (EditText) findViewById(R.id.birthday);
        String outputFormat = null;
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
        String inputFormatStr = "MMMM dd, yyyy";
        DateFormat inputDateFormat = new SimpleDateFormat(inputFormatStr,Locale.US);
        Date inputDate = null;
        try{
            inputDate = inputDateFormat.parse(birthDate.getText().toString());
            if(birthDate!=null){
                outputFormat = formatDate.format(inputDate);
            }
        } catch (ParseException e) {
            Log.e(TAG, "exception occurred with details: "+e.toString());
        }
            return outputFormat;
    }