how to change format of date from string date

前端 未结 4 1088
天命终不由人
天命终不由人 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:17

    Try the code below that will work

    1) Make method like below

    public String changeDateFormat(String currentFormat, String requiredFormat, String dateString) {
            String result = "";
    
            SimpleDateFormat formatterOld = new SimpleDateFormat(currentFormat, Locale.getDefault());
            SimpleDateFormat formatterNew = new SimpleDateFormat(requiredFormat, Locale.getDefault());
            Date date = null;
            try {
                date = formatterOld.parse(dateString);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (date != null) {
                result = formatterNew.format(date);
            }
            return result;
        }//end of changeDateFormat()
    

    1st argument of the method is your current date format in your case it will be 'dd-MM-yyyy'

    2nd argument is output or requires date format in your case it will be 'yyyy-MM-dd'

    3rd argument is your date that you want to change the format

    2) Run the method like below

    String oldFormatDate = "11-12-2018";
    String myDate = changeDateFormat("dd-MM-yyyy", "yyyy-MM-dd", oldFormatDate);
    Log.d(TAG, "Old formatted Date : " + oldFormatDate);
    Log.d(TAG, "New Date is : " + myDate);
    

    3) Output:

    Old formatted Date : 11-12-2018
    New Date is : 2018-12-11
    

提交回复
热议问题