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

强颜欢笑 提交于 2019-12-07 08:30:55

问题


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?


回答1:


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

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



回答2:


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.



来源:https://stackoverflow.com/questions/19439821/eliminating-the-subtle-whitespace-handling-difference-between-datetimeformat-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!