Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 621
Hakanai Avatar asked Dec 16 '22 05:12

Hakanai


1 Answers

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

str = str.replaceAll("  +", " ");
like image 141
Evgeniy Dorofeev Avatar answered May 01 '23 11:05

Evgeniy Dorofeev