Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

How to parse leniently?

Anonymous
2012-08-31
2012-10-08

  • Anonymous
    2012-08-31

    Probably overlooking something again :-)

    The typical user input tends to be as short as they can get away with, f.i
    typing a single number for the day < 10. Which is the intuitive thingy to do,
    and poses no problem with the old default formatters .

        DateFormat format = DateFormat.getDateInstance(); // default == medium
        Date date = format.parse("1.1.2012");
    

    Can't figure out how to achieve a similar leniency with a DateTimeFormatter.
    The following throws up:

        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .parseLenient()
            .appendLocalized(FormatStyle.MEDIUM, null)
            .toFormatter();
        LocalDate localDate = formatter.parse("1.1.2012", LocalDate.class);
    

    with

        javax.time.format.CalendricalParseException: Text '1.1.2012' could not be parsed at index 0
        at javax.time.format.DateTimeFormatter.parseToBuilder(DateTimeFormatter.java:320)
        at javax.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:222)
    

    Thanks for any hints!
    Jeanette

     
  • I'm guessing your locale is GERMANY or similar, as that displays the behaviour
    above.

    Right now, you are correct that the string cannot be parsed in 310. The new
    code is stricter, for example to ensure the correct format of an ISO formatted
    date. I think however that it makes sense to change the code such that lenient
    parsing allows any number of digits to be a successful parse. This needs to be
    implemented and tested...