Eliminate the subtle difference in handling spaces between DateTimeFormat and Joda DateTimeFormatter

We have some existing code:

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 converting it to use Joda Time 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 that the existing test cases broke. In particular (at least the first line that causes the test to fail):

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

DateFormat happily matches two or more spaces after the decimal point, but DateTimeFormatter only matches one space literally.

Maybe I could add an extra format that allows the use of extra space, but it's awful because there is some way to tweak the DateTimeFormatter to be more relaxed with respect to spaces?

+3
source share
1 answer

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

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

All Articles