LocalDate now = LocalDate.now(); String day = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); String time = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
在执行到String time = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));抛出异常,错误信息如下:
1 2 3 4 5 6 7 8 9
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay at java.time.LocalDate.get0(LocalDate.java:680) at java.time.LocalDate.getLong(LocalDate.java:659) at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298) at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2540) at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179) at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746) at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720) at java.time.LocalDate.format(LocalDate.java:1691)
到jdk源码中查看:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
privateintget0(TemporalField field){ switch ((ChronoField) field) { case DAY_OF_WEEK: return getDayOfWeek().getValue(); case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((day - 1) % 7) + 1; case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((getDayOfYear() - 1) % 7) + 1; case DAY_OF_MONTH: return day; case DAY_OF_YEAR: return getDayOfYear(); case EPOCH_DAY: thrownew UnsupportedTemporalTypeException("Invalid field 'EpochDay' for get() method, use getLong() instead"); case ALIGNED_WEEK_OF_MONTH: return ((day - 1) / 7) + 1; case ALIGNED_WEEK_OF_YEAR: return ((getDayOfYear() - 1) / 7) + 1; case MONTH_OF_YEAR: return month; case PROLEPTIC_MONTH: thrownew UnsupportedTemporalTypeException("Invalid field 'ProlepticMonth' for get() method, use getLong() instead"); case YEAR_OF_ERA: return (year >= 1 ? year : 1 - year); case YEAR: return year; case ERA: return (year >= 1 ? 1 : 0); } thrownew UnsupportedTemporalTypeException("Unsupported field: " + field); }
LocalDateTime now = LocalDateTime.now(); String day = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); String time = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));