A Java 8 DateTimeFormatter
created from a pattern like d. MMM u
can only parse dates with the month written in the style defined by TextStyle.SHORT (e.g. 13. Feb 2015
), a DateTimeFormatter created from d. MMMM u
can only parse dates with the month written in the style defined by TextStyle.FULL (e.g. 13. February 2015
).
In the "old" SimpleDateFormat, the difference between "MMM" and "MMMM" was only important for formatting, not for parsing, so it was easily possible to create a parser that understood both the FULL and the SHORT form of month names.
Is it possible to create a Java 8 DateTimeFormatter that can also do this? Or do I always have to create two parsers, one with the FULL and one with the SHORT pattern?
You could make the different month patterns optional:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d. [MMMM][MMM] u HH:mm:ss z", Locale.US);
ZonedDateTime zdt1 = ZonedDateTime.parse("4. Jan 2015 00:00:00 UTC", formatter);
ZonedDateTime zdt2 = ZonedDateTime.parse("4. January 2015 00:00:00 UTC", formatter);
System.out.println(zdt1);
System.out.println(zdt2);
Output:
2015-01-04T00:00Z[UTC]
2015-01-04T00:00Z[UTC]
EDIT
This formatter can only be used for parse()
, you will have to use a different one for format()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With