使用可选解析器从 joda-time DateTimeFormatter 打印

jue*_*ell 4 java datetime jodatime

在使用 joda-time 2.1 的项目中,我有以下内容DateTimeFormatter

   /**
   * Parser for the "fraction" part of a date-time value.
   */
  private static final DateTimeParser FRACTION_PARSER =
      new DateTimeFormatterBuilder()
          .appendLiteral('.')
          .appendFractionOfSecond(3, 9)
          .toParser();

  /**
   * A formatter for a "local" date/time without time zone offset
   * (in the format "yyyy-dd-mmThh:mm:ss[.fff]").
   */
  private static final DateTimeFormatter FORMAT_LOCAL =
      new DateTimeFormatterBuilder()
          .append(ISODateTimeFormat.date())
          .appendLiteral('T')
          .append(ISODateTimeFormat.hourMinuteSecond())
          .appendOptional(FRACTION_PARSER)
          .toFormatter()
          .withZone(DateTimeZone.UTC);
Run Code Online (Sandbox Code Playgroud)

它正是我想要的。它解析带或不带分数的日期,并打印不带分数的日期。

如果我升级到 joda-time 的更新版本,我会得到

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.UnsupportedOperationException: Printing is not supported
    at org.joda.time.format.DateTimeFormatterBuilder.toPrinter(DateTimeFormatterBuilder.java:136)
Run Code Online (Sandbox Code Playgroud)

所以我想我之前遇到的是一个错误,但它确实做了我想做的事情!我如何获得相同的行为而不犯错误?我尝试过使用append(DateTimePrinter, DateTimeParser[])空打印机和实际上不打印任何内容的打印机,但它们都不起作用。

jue*_*ell 5

所以我最终想通了,解决方案是分别构建完整的解析器和打印机,如下所示:

  /**
   * Parser for the "fraction" part of a date-time value.
   */
  private static final DateTimeParser FRACTION_PARSER =
      new DateTimeFormatterBuilder()
          .appendLiteral('.')
          .appendFractionOfSecond(3, 9)
          .toParser();

  private static final DateTimeParser BASE_PARSER =
      new DateTimeFormatterBuilder()
          .append(ISODateTimeFormat.date())
          .appendLiteral('T')
          .append(ISODateTimeFormat.hourMinuteSecond())
          .appendOptional(FRACTION_PARSER)
          .toParser();

  private static final DateTimePrinter BASE_PRINTER =
      new DateTimeFormatterBuilder()
          .append(ISODateTimeFormat.date())
          .appendLiteral('T')
          .append(ISODateTimeFormat.hourMinuteSecond())
          // omit fraction of second
          .toPrinter();

  /**
   * A formatter for a "local" date/time without time zone offset
   * (in the format "yyyy-dd-mmThh:mm:ss[.fff]").
   */
  private static final DateTimeFormatter FORMAT_LOCAL =
      new DateTimeFormatterBuilder()
          .append(BASE_PRINTER, BASE_PARSER)
          .toFormatter()
          .withZone(DateTimeZone.UTC);
Run Code Online (Sandbox Code Playgroud)