我可以让 JodaTime DateTimeFormat 对日期的毫秒数宽松一些吗?

Can I make JodaTime DateTimeFormat lenient about the milliseconds of a date?

我的单元测试失败了,我想让它通过:

@Test
public void testDateFormatsWithNo() throws Exception {
    List<String> dateStrings = Lists.newArrayList("2014-08-02T22:21:32Z", "2014-05-27T17:11:55.597Z");
    try {
        String twoMillis = "yyyy-MM-dd'T'HH:mm:ss'Z'";
        for (String dateString : dateStrings) {
            DateTimeFormat.forPattern(twoMillis).parseDateTime(dateString);
        }
    } catch (Exception e) {
        fail(e.getMessage());
    }
}

@Test
public void testDateFormatsWithThreeMillis() throws Exception {
    List<String> dateStrings = Lists.newArrayList("2014-08-02T22:21:32Z", "2014-05-27T17:11:55.597Z");
    try {
        String threeMillis = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
        for (String dateString : dateStrings) {
            DateTimeFormat.forPattern(threeMillis).parseDateTime(dateString);
        }
    } catch (Exception e) {
        fail(e.getMessage());
    }
}

失败并分别显示以下错误消息:

java.lang.AssertionError: Invalid format: "2014-05-27T17:11:55.597Z" is malformed at ".597Z"
java.lang.AssertionError: Invalid format: "2014-08-02T22:21:32Z" is malformed at "Z"

我想知道是否有 单一 日期格式模式可用于解析这两个日期字符串。如您所见,有些字符串有 2 毫秒,有些有 3 毫秒。这可能吗?

为了正确处理您输入的 Z 符号,您的模式不正确,因为字母 Z 不是文字而是代表 UTC+00:00。以下解决方案适合您(您可以根据需要调整精度):

DateTimeParser[] parsers = { 
  new DateTimeFormatterBuilder()
    .appendLiteral('.')
    .appendFractionOfSecond(2, 3) // or even set min-digits to 1
    .appendTimeZoneOffset("Z", true, 1, 2)
    .toParser(),
  new DateTimeFormatterBuilder()
    .appendTimeZoneOffset("Z", true, 1, 2)
    .toParser()};
DateTimeFormatter dtf =
  new DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd'T'HH:mm:ss")
    .append(null, parsers)
    .toFormatter();
String input = "2014-08-02T22:21:32.123Z";
System.out.println(dtf.parseDateTime(input));
// in my timezone: 2014-08-03T00:21:32.123+02:00

input = "2014-08-02T22:21:32.12Z";
System.out.println(dtf.parseDateTime(input));
// 2014-08-03T00:21:32.120+02:00

input = "2014-08-02T22:21:32Z";
System.out.println(dtf.parseDateTime(input));
// 2014-08-03T00:21:32.000+02:00