Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to parse dates with both TextStyle.SHORT and TextStyle.FULL for the month?

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?

like image 803
David Avatar asked Sep 12 '15 15:09

David


1 Answers

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().

like image 189
Cinnam Avatar answered Oct 04 '22 10:10

Cinnam