String.replaceFirst() and java.time through ThreeTenABP
There are some different ways to go about it. I present a kind of mixed approach: I am using a regular expression for the different possible delimiters, which validates that both delimiters (after day and after month) are the same. Next I am using optional parts in the format pattern string to handle month as either abbreviation (Jan
) or number (01
).
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-[MMM][MM]-uuuu", Locale.ENGLISH);
String[] inputs = { "02/01/2020", "04-01-2020", "07 01 2020",
"09 Jan 2020", "13-Jan-2020", "17/Jan/2020" };
for (String input : inputs) {
String withHyphens = input.replaceFirst("([/ ])(.*)\\1", "-$2-");
LocalDate date = LocalDate.parse(withHyphens, dateFormatter);
System.out.format("%11s was parsed into %s%n", input, date);
}
Output from this smippet is:
02/01/2020 was parsed into 2020-01-02
04-01-2020 was parsed into 2020-01-04
07 01 2020 was parsed into 2020-01-07
09 Jan 2020 was parsed into 2020-01-09
13-Jan-2020 was parsed into 2020-01-13
17/Jan/2020 was parsed into 2020-01-17
If you prefer, you may also use optional parts in the format pattern string for everything. Then your format pattern may look like dd[/][-][ ][MMM][MM][/][-][ ]uuuu
. It gives more lenient validation, but is more consistent and shorter.
I am using the backport of java.time, the modern Java date and time API.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links