将Instant格式化为字符串时发生UnsupportedTemporalTypeException [英] UnsupportedTemporalTypeException when formatting Instant to String

查看:51
本文介绍了将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)
    ...

推荐答案

时区

需要

格式化Instantatime-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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆