将从DatePickerDialog获取的日期格式转换为yyyy-MM-dd

时间:2019-04-02 11:06:10

标签: android date simpledateformat android-datepicker

我想将日期格式转换为yyyy-MM-dd,我从DatePickerDialog获取并将日期存储在editext中,并将日期检索为字符串,我在String中获取的日期格式为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);
    }

//出现错误  java.lang.IllegalArgumentException

2 个答案:

答案 0 :(得分:0)

尝试这个@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);

答案 1 :(得分:0)

尝试一下可能会对您有所帮助

public static String parseDate(String inputDateString, SimpleDateFormat inputDateFormat, SimpleDateFormat outputDateFormat) {
    Date date = null;
    String outputDateString = null;
    try {
        date = inputDateFormat.parse(inputDateString);
        outputDateString = outputDateFormat.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return outputDateString;
}

如何拨打电话

public static final SimpleDateFormat inputFormat = new SimpleDateFormat("mm-dd-yyyy", Locale.getDefault());

public static final SimpleDateFormat outPutForamt = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

private String outputDateStr = "";

outputDateStr = parseDate("04-02-2019", inputFormat , outPutForamt );

Log.i("output_string", outputDateStr);