- You can use
DateTimeFormatterBuilder#parseDefaulting
and keep the optional patterns inside the square bracket.
- I also strongly suggest to use
DateTimeFormatterBuilder#parseCaseInsensitive
to deal with case (e.g. AM/am).
- Also, never forget to use
Locale
with a DateTimeFormatter
because it is a Locale
-sensitive type.
- Last but not the least, note that
H
is use for 24-hour format while h
is used for 12-hour format.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("[MM/dd/uuuu hh:mm:ss a][MM/dd/uuuu HH[:mm[:ss]]][uuuuMMdd[ hh:mm:ss a]")
.parseDefaulting(ChronoField.CLOCK_HOUR_OF_AMPM, 0)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter(Locale.ENGLISH);
// Test
String[] arr = { "08/25/2021 10:20:30 am", "08/25/2021 10:20:30", "08/25/2021 10:20", "20210825" };
for (String s : arr) {
LocalDateTime ldt = LocalDateTime.parse(s, dateFormatter);
System.out.println(ldt);
}
}
}
Output:
2021-08-25T10:20:30
2021-08-25T10:20:30
2021-08-25T10:20
2021-08-25T00:00
ONLINE DEMO
Note: You can use y
instead of u
but I prefer u
to y
.
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.