A single y
can parse the years of one+ digits
Caution: A two-digit year will be parsed as a year without a century e.g. 19
will be parsed as 0019
. If you want it to be 2019
, use yy
.
Demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/y", Locale.ENGLISH);
Stream.of(
"01/01/1",
"01/01/19",
"01/01/192",
"01/01/1921",
"01/01/19211"
).forEach( s -> System.out.println(LocalDate.parse(s, dtf)));
}
}
Output:
0001-01-01
0019-01-01
0192-01-01
1921-01-01
+19211-01-01
ONLINE DEMO
Therefore, you need to get the value of the year from the resulting date and validate the year e.g.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/y", Locale.ENGLISH);
int year = LocalDate.parse("01/01/19211", dtf).getYear();
if (year < 1900 || year > 9999) {
// Do this
} else {
// Do that
}
}
}
You may also like to check prefer u
to y
.
Learn more about the modern Date-Time API from Trail: Date Time.
Note: 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*.
* 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.