Hakanai
Hakanai

Reputation: 12680

Eliminating the subtle whitespace handling difference between DateTimeFormat and Joda's DateTimeFormatter

We have some existing code like this:

DateFormat[] dateFormats = {
    new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH),
    new SimpleDateFormat("d MMM yyyy HH:mm:ss Z", Locale.ENGLISH)
};

For thread safety reasons, I tried to convert it to use Joda Time's formatters, so:

DateTimeFormatter[] dateFormats = {
    DateTimeFormat.forPattern("EEE, d MMM yyyy HH:mm:ss Z")
                  .withLocale(Locale.ENGLISH)
                  .withOffsetParsed(),
    DateTimeFormat.forPattern("d MMM yyyy HH:mm:ss Z")
                  .withLocale(Locale.ENGLISH)
                  .withOffsetParsed()
};

However, it surprised me to find that existing test cases broke. In particular (at least the first line which causes the test to fail):

String dateString = "Wed,  1 Feb 2006 21:58:41 +0000";

DateFormat happily matches two or more spaces after the comma but DateTimeFormatter only matches the single space literally.

I could probably put in an additional format which allows for an additional space, but it is sort of awful to have to do that, so is there some way to customise a DateTimeFormatter to be more relaxed about whitespace?

Upvotes: 4

Views: 3463

Answers (2)

Aleksandr Gromov
Aleksandr Gromov

Reputation: 66

I think it will be useful for others saying that since Java 8 we can fix above issue by rewriting the pattern:

String pattern = "EEE,[  ][ ]d MMM yyyy HH:mm:ss Z"

This code matches 1 or 2 spaces after comma.

Upvotes: 4

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

I think it's much easier to process the input string before parsing

str = str.replaceAll("  +", " ");

Upvotes: 8

Related Questions