消除DateTimeFormat和Joda的DateTimeFormatter之间的细微空白处理差异 [英] Eliminating the subtle whitespace handling difference between DateTimeFormat and Joda's DateTimeFormatter

查看:174
本文介绍了消除DateTimeFormat和Joda的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)
};

出于线程安全的原因,我尝试将其转换为使用Joda Time的格式化程序,因此:

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在逗号后愉快地匹配两个或多个空格,但DateTimeFormatter仅在字面上匹配单个空格。

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

我可能会采用其他格式,以留出额外的空间,但是这样做很糟糕,因此有某种方法可以自定义DateTimeFormatter来

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?

推荐答案

我认为在解析之前处理输入字符串要容易得多

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

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

这篇关于消除DateTimeFormat和Joda的DateTimeFormatter之间的细微空白处理差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆