格式化Instant到字符串的那些手段| Java Debug 笔记

1,748 阅读1分钟

本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看 活动链接

image.png

前言

如何采用Java的jdk1.8的API来实现,对于Instant格式化为字符串呢?

相信很多人可能都不是很清晰,我们就来聊一下这个话题。

问题复现

当在如下的场景时

Instant instant = ...;
String out = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(instant);

想要通过使用Jdk1.8的时间Api来进行格式化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一个问题是需要了解的,那就是time zone。

没有时区,将无法进行格式化到人类的时间定义。

时区可以通过以下代码,被添加到格式器上去

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

如果有针对性特殊要求,想要使用ISO-8601 进行格式化编码,则需要修改下上述代码

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

总结

格式化并不难,难得是熟练运行相关的API。