java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API:
DateTimeFormatterBuilder
allows building a DateTimeFormatter
with default time units. Also, you can specify optional parts of the pattern using a square bracket or by using the .optionalXXX
function of DateTimeFormatterBuilder
.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
DateTimeFormatter parser = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-dd['T'][ ]HH:mm[:ss]")
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter(Locale.ENGLISH);
// Test
Stream.of(
"2021-07-10T10:20:30",
"2021-07-10 10:20:30",
"2021-07-10T10:20",
"2021-07-10 10:20"
).forEach(s -> System.out.println(LocalDateTime.parse(s, parser)));
}
}
Output:
2021-07-10T10:20:30
2021-07-10T10:20:30
2021-07-10T10:20
2021-07-10T10:20
ONLINE DEMO
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.