【问题标题】:LocalDateTime format() throw java.time.temporal.UnsupportedTemporalTypeExceptionLocalDateTime 格式()抛出 java.time.temporal.UnsupportedTemporalTypeException
【发布时间】:2022-10-13 12:50:26
【问题描述】:

问题描述:

我现在想用格式化程序模式从LocalDateTime.now() 格式化日期时间 yyyy-MM-dd HH:mm Z

抛出 UnsupportedTemporalTypeException 的完整代码:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatter_UnsupportedTemporalTypeException {

    public static void main(String[] args) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm Z");
        String format = fmt.format(LocalDateTime.now());
        System.out.println(format);
    }
}

当我运行这段代码时,我得到了这个堆栈跟踪:

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds
    at java.time.LocalDate.get0(LocalDate.java:680)
    at java.time.LocalDate.getLong(LocalDate.java:659)
    at java.time.LocalDateTime.getLong(LocalDateTime.java:720)
    at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
    at java.time.format.DateTimeFormatterBuilder$OffsetIdPrinterParser.format(DateTimeFormatterBuilder.java:3346)
    at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2190)
    at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746)
    at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720)

【问题讨论】:

    标签: java date localdatetime datetimeformatter


    【解决方案1】:

    解决方案:

    // to solve this exception use:

    ZonedDateTime.now()

    // eg: String format = fmt.format(ZonedDateTime.now());

    // instead of using:

    LocalDateTime.now()

    最终代码:

    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    
    public class DateTimeFormatter_UnsupportedTemporalTypeException_Solution {
    
        public static void main(String[] args) {
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm Z");
            String format = fmt.format(ZonedDateTime.now());
            System.out.println(format); // 2019-10-04 22:55 +0200
        }
    }
    

    输出:

    2019-10-04 22:55 +0200

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 2014-07-11
      • 2012-03-26
      相关资源
      最近更新 更多