How to convert date from this format "dd/MMM/yyyy" to any other format with Java 17 version?

428 Views Asked by At

I am trying to convert date from this format "dd/MMM/yyyy" to "yyyyMMdd", for Java 1.8 version ,the code was working fine, my code is

       SimpleDateFormat inputFormat = new SimpleDateFormat(currentFormat);
       SimpleDateFormat outputFormat = new SimpleDateFormat(newFormat);
       Date date = inputFormat.parse(dateStr);
       return outputFormat.format(date);

when i changed from Java 8 to java 17 , I am getting parse Exception. Please help, thanks

2

There are 2 best solutions below

1
Oleg Cherednik On

For jvm17 do use java.time.* instead.

public static String convert(String dateStr) {
    LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("dd/MMM/yyyy", Locale.ENGLISH));
    return date.format(DateTimeFormatter.BASIC_ISO_DATE, Locale.ENGLISH);
}

And the client's code will look like this:

String dateStr = "22/Jul/2023";
System.out.println(convert(dateStr));   // 20230722 
0
WJS On

Unless it is a backward compatible requirement you should avoid the old Date classes and their supporting classes. They are buggy and obsolete.

From the java.time package.

What you want is the BASIC_ISO_DATE which is predefined. So all that is required is the from format. Add locales as appropriate for your requirements.

String dateString = "10/Jan/2023";
 
DateTimeFormatter from = DateTimeFormatter.ofPattern("dd/MMM/yyyy", Locale.ENGLISH);
LocalDate ldt = LocalDate.parse(dateString, from);
String result = ldt.format(DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(result);

prints

20230110

Check out the java.time package for a rich set of classes to manipulate various dates and times.