我正在try 使用新的Java 8日期和时间API和以下模式将瞬间格式化为字符串:

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)
    ...

推荐答案

Time Zone

要设置Instant的格式,需要time-zone.如果没有时区,格式化程序不知道如何将即时时间字段转换为人工日期时间字段,因此会引发异常.

时区可以使用withZone()直接添加到格式化程序中.

DateTimeFormatter formatter =
    DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                     .withLocale( Locale.UK )
                     .withZone( ZoneId.systemDefault() );

如果您特别需要没有显式时区的ISO-8601格式 (如操作员所问),with the time-zone implicitly UTC,你需要

DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))

Generating String

现在使用该格式化程序生成Instant的字符串表示形式.

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 );

run 的时候.

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

Java相关问答推荐

PDFBox SmallMap不尊重Map.入口哈希码合同

虚拟线程似乎在外部服务调用时阻止运营商线程

neo4j java驱动程序是否会在错误发生时自动回滚事务?

替换com. sun. jndi. dns. DnsContextFactory Wildfly23 JDK 17

@ IdClass with @ Inheritance(策略= InheritanceType. SINGLE_TABLE)

有没有一种方法使保持活动设置专用于java.net.http.HttpClient的一个实例

什么是Java原子属性的正确getter和setter

带错误BER验证的itext8签名返回pdf

从ActiveMQ Classic迁移到ActiveMQ Artemis需要进行哪些客户端更改?

在执行流和相关操作时,使用Java泛型为2个方法执行相同的操作,但对象不同

无法使用Freemarker从XML中读取重复的标记值

如何在IntelliJ IDEA的Build.sbt中添加外部JAR文件?

对角线填充二维数组

使IntelliJ在导入时优先 Select 一个类或将另一个标记为错误

在打开搜索结果时,如何让Eclipse打开整个文件?

为什么项目名称出现在我的GET请求中?

TinyDB问题,无法解析符号';上下文&

为什么我的登录终结点不能被任何请求访问?

在Spring Boot中使用咖啡因进行缓存-根据输出控制缓存

将@Transactional添加到Spring框架中链下的每个方法会产生什么效果?