在Java 8 Date Time API中,我将使用DateTimeFormatter API来打印时间,如下所示:

DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL);
LocalTime time = LocalTime.of(12, 45, 0);
System.out.println(timeFormatter.format(time));
FormatStyle.FULL-这种格式样式适合LocalDateLocalDateTime实例。但是,使用LocalTime实例抛出异常:
java.time.DateTimeException: Unable to extract value: class java.time.format.DateTimePrintContext$1

根据文档:
public enum FormatStyle {
    // ordered from large to small

    /**
     * Full text style, with the most detail.
     * For example, the format might be 'Tuesday, April 12, 1952 AD' or '3:30:42pm PST'.
     */
    FULL,

为什么会引发异常?

最佳答案

好像您被JDK-JDK-8085887: java.time.format.FormatStyle.LONG or FULL causes unchecked exception击中(JDK 9中已修复)。

出现该异常的原因在该处的第一条评论中指出:



注释还指出,由于模式不同,这是语言环境的依赖,但这可能与您的情况无关。不过,我将其包括在内以供引用:



在查看差异时(例如 DateTimeFormatter 中),您会看到他们只是更新了Javadoc来反射(reflect)这一点(对异常消息进行了一些其他改进):

@@ -617,10 +617,13 @@
      * looking up the pattern required on demand.
      * <p>
      * The returned formatter has a chronology of ISO set to ensure dates in
      * other calendar systems are correctly converted.
      * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style.
+     * The {@code FULL} and {@code LONG} styles typically require a time-zone.
+     * When formatting using these styles, a {@code ZoneId} must be available,
+     * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}.
      *
      * @param timeStyle  the formatter style to obtain, not null
      * @return the time formatter, not null
      */
     public static DateTimeFormatter ofLocalizedTime(FormatStyle timeStyle) {

如果您将时区添加到DateTimeFormatter实例,则它可以正常工作:
DateTimeFormatter timeFormatter = DateTimeFormatter
                                      .ofLocalizedTime(FormatStyle.FULL)
                                      .withZone(ZoneId.systemDefault());
LocalTime time = LocalTime.of(12, 45, 0);
System.out.println(timeFormatter.format(time));

10-08 15:09