elvis
elvis

Reputation: 1208

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!

Upvotes: 0

Views: 129

Answers (2)

g00se
g00se

Reputation: 4292

java.time

Don't use superseded date classes. Date, SimpleDateFormat - no! LocalDate , DateTimeFormatter - yes!

And the formatting pattern is case-sensitive. For abbreviated name of month, use uppercase ‘MMM’.

Specify a Locale to be used in determining the human language and cultural norms for localizing that name of month.

String oldDate = "05-Apr-23";
DateTimeFormatter dfFrom = DateTimeFormatter.ofPattern("dd-MMM-yy").withLocale( Locale.US );
DateTimeFormatter dfTo = DateTimeFormatter.ofPattern("dd/MM/yy");
String newDate = dfTo.format(LocalDate.parse(oldDate, dfFrom));
System.out.println(newDate);

Upvotes: 3

Mayuri
Mayuri

Reputation: 101

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.

Upvotes: 4

Related Questions