how to change format of date from string date

前端 未结 4 1129
天命终不由人
天命终不由人 2021-01-29 09:27

I have date as a string like this

String date = \"11-12-2018\"

I want to change it to \"2018-12-11\"

with the same var

4条回答
  •  情深已故
    2021-01-29 10:21

    This is the common function which I use for date and time conversion

    public String convertDateAndTime(String date, String oldFormat, String newFormat) {
            SimpleDateFormat sdf = new SimpleDateFormat(oldFormat);
            Date currentdate;
            String converted = "";
            try {
                currentdate = sdf.parse(date);
                SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);
                converted = sdf2.format(currentdate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return converted;
        }
    

    You just have to pass the date string and their old and new formats. In your case call this function like this

    String converteddate = convertDateAndTime("11-12-2018","dd-mm-yyyy","yyyy-MM-dd");
    

提交回复
热议问题