-1

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

  • 1
    Note that the classes ur using there are all outdated. Prefer using the stuff from `java.time` instead. – Zabuzard Jul 26 '23 at 14:24
  • 1
    What input are you using? – DuncG Jul 26 '23 at 14:53
  • Which is your default locale? Is it the same in your Java 17 installation as in your Java 8 installation? Also please at least post the full message from the exception. – Ole V.V. Aug 04 '23 at 17:46
  • Java’s locale data — including the abbreviations for months in different languages — changed a lot from Java 8 to Java 9 and have had further changes since. This is a probable explanation for your error, but without more details and a [mre] we can’t tell whether it is the reason. See more in [this question](https://stackoverflow.com/questions/46244724/jdk-dateformater-parsing-dayofweek-in-german-locale-java8-vs-java9) and [this one](https://stackoverflow.com/questions/66394366/cannot-convert-from-spanish-date-string-to-localdate-in-java). – Ole V.V. Aug 04 '23 at 17:51

2 Answers2

2

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 
UkFLSUI
  • 5,509
  • 6
  • 32
  • 47
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
2

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
WJS
  • 36,363
  • 4
  • 24
  • 39