Search code examples
javaandroiddatetimeandroid-datepicker

How to store two different dateFormat strings into two variables


I have an EditText on which click event I am showing the DatePicker Dialog Box and displaying the choosen date in "MMMM dd, yyyy" format i.e June 26, 1932 . But I need to pass the date in the different format to the server; format which I need to pass is "1932-06-26" . Below is my code :

       {
    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));
    }

And for storing the date in different format, I am following below method :

 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);

But I am getting an java.lang.IllegalArgumentException: Bad class: class java.lang.String error.

Is it at all possible to display date in one format and store the date into different format?


Solution

  • Try this

        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);