本文介绍了格式化即时到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用新的java 8 time-api格式化一个即时到一个String即时即时= ...;
String out = DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm:ss)。format(instant);
使用上面的代码,我得到一个不受支持的字段的异常:
java.time.temporal.UnsupportedTemporalTypeException:不支持的字段:YearOfEra
在java.time.Instant.getLong(Instant.java:608)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
...
解决方案
时区
要格式化 a 。没有时区,格式化程序不知道如何将瞬间转换为人类日期时间字段,因此会抛出异常。
时区可以是直接添加到格式化器使用。
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(Locale.UK)
.withZone(ZoneId.systemDefault());
生成字符串
现在使用格式化生成您的Instant的String表示。
即时即时= Instant.now();
String output = formatter.format(instant);
转储到控制台。
System.out.println(formatter:+ formatter +with zone:+ formatter.getZone()+和Locale:+ formatter.getLocale());
System.out.println(instant:+ instant);
System.out.println(output:+ output);
运行时
formatter:本地化(SHORT,SHORT)区域:US / Pacific和Locale:en_GB
即时:2015-06-02T21:34:33.616Z
输出:02/06/15 14:34
I'm trying to format an Instant to a String using the new java 8 time-api and a pattern:
Instant instant = ...;
String out = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(instant);
Using the code above I get an Exception which complains an unsupported field:
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
To format an Instant
a time-zone is required. Without a time-zone, the formatter does not know how to convert the instant to human date-time fields, and therefore throws an exception.
The time-zone can be added directly to the formatter using withZone()
.
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
.withLocale( Locale.UK )
.withZone( ZoneId.systemDefault() );
Generating String
Now use that formatter to generate the String representation of your Instant.
Instant instant = Instant.now();
String output = formatter.format( instant );
Dump to console.
System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );
When 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
这篇关于格式化即时到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!