java.time
The legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time
, the modern date-time API*.
The format, yyyyMMdd
is actually wrong for the string, 100 112TH AVE NE
. The correct format would be y Mdd
or y MMd
. You can use yyy
instead of a single y
in any of these two formats. However, instead of throwing the relevant exception, it silently parsed the string erroneously.
Apart from this, note the following line from the documentation of SimpleDateFormat
:
Parses text from the beginning of the given string to produce a date.
The method may not use the entire text of the given string.
Using modern date-time API:
Unlike SimpleDateFormat
, the modern date-time API is strict (doesn't assume the things in most cases) in terms of format which makes it much cleaner. It requires specifying the things explicitly to avoid ambiguity e.g. you can use ParsePosition
to parse the given date-time string and thus you can see clearly what is happening.
Demo:
import java.text.ParsePosition;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String args[]) {
System.out.println(
LocalDate.from(DateTimeFormatter.ofPattern("u Mdd").parse("100 112TH AVE NE", new ParsePosition(0))));
System.out.println(
LocalDate.from(DateTimeFormatter.ofPattern("u MMd").parse("100 112TH AVE NE", new ParsePosition(0))));
}
}
Output:
0100-01-12
0100-11-02
Learn more about the 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.