UnsupportedTemporalTypeException when formatting Instant to String(将Instant格式化为字符串时发生UnsupportedTemporalTypeException)
本文介绍了将Instant格式化为字符串时发生UnsupportedTemporalTypeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用新的Java 8日期和时间API和以下模式将Instant格式化为字符串:
Instant instant = ...;
String out = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(instant);
使用上面的代码,我得到一个异常,它报告不受支持的字段:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
at java.time.Instant.getLong(Instant.java:608)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
...
推荐答案
时区
需要格式化Instant
atime-zone。没有时区,格式化程序不知道如何将即时转换为人工日期时间字段,因此引发异常。
可以使用withZone()
将时区直接添加到格式化程序。
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
.withLocale( Locale.UK )
.withZone( ZoneId.systemDefault() );
如果您特别需要没有显式时区的ISO-8601格式
(按照操作员的要求),对于隐式UTC时区,您需要
DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))
正在生成字符串
现在使用该格式化程序生成您的即时消息的字符串表示形式。
Instant instant = Instant.now();
String output = formatter.format( instant );
转储到控制台。
System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );
运行时。
formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
instant: 2015-06-02T21:34:33.616Z
output: 02/06/15 14:34
这篇关于将Instant格式化为字符串时发生UnsupportedTemporalTypeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:将Instant格式化为字符串时发生UnsupportedTemporalTypeException


猜你喜欢
- 如何指定 CORS 的响应标头? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 获取数字的最后一位 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 转换 ldap 日期 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01