Search code examples
javaspringdatesimpledateformatparseexception

How to convert a date into another date as a String in Java?


I want to convert a date format into another date format. For example, I have this String "05-Apr-23" and I want to convert it into this String "05/04/23". And I did this implementation but it's not working.

String oldDate = "05-Apr-23";
SimpleDateFormat sdf = new SimpleDateFormat("dd-mmm-yy");
Date dt = null;
try {
    dt = sdf.parse(oldDate);
} catch (ParseException e) {
    throw new CustomInternalServerException(oldDate + "is not a valid date");
}

SimpleDateFormat sdf1 = new SimpleDateFormat("dd/mm/yy");
return sdf1.format(dt);

I get the exception ParseException: UnparseableDate: "05-Apr-23". Any feedback will be appreciated! Thank you!


Solution

  • You did only one small mistake you have to use MMM instead of mmm , m is used for minute and M is for month.

    change as follow

    dd-mmm-yy to dd-MMM-yy
    dd/mm/yy to dd/MM/yy
    

    and one more mistake at last you have to return sdf1 not sdf.