Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local date parsing not working without separators

I have a date formatted in the following way :

The year in four digits then the week number in two digits.

For instance, the fourth week of 2018 will be 201804.

I'm having trouble parsing these dates using Java 8's LocalDate and DateTimeFormatterBuilder.

Here is how I try to parse the date :

LocalDate.parse(
    "201804",
    new DateTimeFormatterBuilder().appendPattern("YYYYww").parseDefaulting(WeekFields.ISO.dayOfWeek(), 1).toFormatter()
);

The execution throws the following exception :

java.time.format.DateTimeParseException: Text '201804' could not be parsed at index 0

The odd behavior is that, when I add a separator between the date parts, the exception is not thrown anymore :

LocalDate.parse(
    "2018 04",
    new DateTimeFormatterBuilder().appendPattern("YYYY ww").parseDefaulting(WeekFields.ISO.dayOfWeek(), 1).toFormatter()
);

Results in :

2018-01-22

Is there a thing I am missing with the formatter ?

like image 258
Thomas Ferro Avatar asked Mar 04 '23 14:03

Thomas Ferro


1 Answers

You can use appendValue

This method supports a special technique of parsing known as 'adjacent value parsing'. This technique solves the problem where a value, variable or fixed width, is followed by one or more fixed length values. The standard parser is greedy, and thus it would normally steal the digits that are needed by the fixed width value parsers that follow the variable width one.

No action is required to initiate 'adjacent value parsing'. When a call to appendValue is made, the builder enters adjacent value parsing setup mode.

So this works:

LocalDate.parse(
                "201804",
                new DateTimeFormatterBuilder()
                        .appendValue(YEAR, 4)
                        .appendValue(ALIGNED_WEEK_OF_YEAR, 2)
                        .parseDefaulting(WeekFields.ISO.dayOfWeek(), 1).toFormatter()
        );
like image 195
Eran Avatar answered Mar 14 '23 20:03

Eran