I’ve date format like Apr 1 2022 12:00:00:000AM and looking to convert it into 20220401 (yyyyMMdd).How can we convert the Date format
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Demo {
public static void main(String[] args) {
String value = "Apr 1 2022 12:00:00:000AM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm:ss.SSSa");
LocalDateTime dateTime = LocalDateTime.parse(value, formatter);
System.out.println(dateTime);
}
}
When run this code giving me below error
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Apr 1 2022 12:00:00:000AM' could not be parsed at index 4
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at Demo.main(Demo.java:10)
EDIT-1
As per Basil Bourque suggestions, still below is not working
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Demo {
public static void main(String[] args) {
String value = "Apr 1 2022 12:00:00:000AM".replace( " " , " " ) ;
Locale locale = new Locale.Builder().setLanguage("en").setRegion("US").build();
DateTimeFormatter formatter =
DateTimeFormatter.
ofPattern("MMM d yyyy hh:mm:ss.SSSa")
.withLocale( locale ) ;
LocalDateTime dateTime = LocalDateTime.parse(value, formatter);
System.out.println(dateTime);
}
}
Still the same error
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Apr 1 2022 12:00:00:000AM' could not be parsed at index 19
>Solution :
You have several errors in your DateTimeFormatter.
- There are two spaces between the month and the day. That’s why Java is giving you the following error:
java.time.format.DateTimeParseException: Text ‘Apr 1 2022 12:00:00:000AM’ could not be parsed at index 4
-
As @Basil has written in his answer, you better pass a
Localeto parse correctly your date, sinceAprwon’t be parsed if you’re on a different system like the Italian one, for example, which accepts onlyapr. -
Lastly, you have a colon (
:) to separate seconds and milliseconds, while your value contains a dot (.).
This is the fixed version of your code:
public class Demo {
public static void main(String[] args) {
String value = "Apr 1 2022 12:00:00:000AM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm:ss:SSSa", Locale.US);
LocalDateTime dateTime = LocalDateTime.parse(value, formatter);
System.out.println(dateTime);
}
}
Disclaimer: I made changes only to your DateTimeFormatter supposing that you would have to abide to this specific format. However, if you are constructing the values to parse, make sure to not add extra white spaces and use standard symbols to separate each group.