Search code examples
androiddatesimpledateformatandroid-datepicker

Convert Date format getting from DatePickerDialog to yyyy-MM-dd


I want to convert the date format to yyyy-MM-dd i am getting from the DatePickerDialog and storing the date in editext, and retrieving the date into string, the date i am getting in String is in the format of mm-dd-yyyy

    public class MainActivity extends AppCompatActivity
            implements NavigationView.OnNavigationItemSelectedListener, EnquiryAdapter.OnItemClickListener {

            String StartDate = mStartDate.getText().toString();
            String endDate = mEndDate.getText().toString();
     private EditText mStartDate, mEndDate;

     private void showFilterDialog(){
            LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
            View filterDialog = layoutInflater.inflate(R.layout.filters,null);


            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
            alertBuilder.setTitle("Filters");
            alertBuilder.setView(filterDialog);

            mStartDate = filterDialog.findViewById(R.id.editText);
            mEndDate = filterDialog.findViewById(R.id.editText2);


            String StartDate = mStartDate.getText().toString();
            String endDate = mEndDate.getText().toString();

 // i have tried this method but getting error
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String sd = format.format(java.sql.Date.parse(StartDate));
            String ed = format.format(Date.parse(endDate));
            Log.d("Start Date", sd);
            Log.d("End Date", ed);
    }

// getting error java.lang.IllegalArgumentException


Solution

  • Try this @Shubham

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calDate; = calDate = Calendar.getInstance();
    calDate.add(Calendar.DAY_OF_YEAR, 0);
    String date = simpleDateFormat.format(calDate.getTime());
    Log.e("result_date",date);