我正在将 Grails Joda-Time 插件转换为JavaTime.
我有旧的乔达时间代码,如下所示:
def style
switch (type) {
case LocalTime:
style = '-S'
break
case LocalDate:
style = 'S-'
break
default:
style = 'SS'
}
Locale locale = LocaleContextHolder.locale
return DateTimeFormatter.ofPattern(style, locale).withResolverStyle(ResolverStyle.LENIENT)
如何将其转换为 JSR 310?
我找不到类似的方法forStyle(字符串样式)它接受风格。
UPD我找到了解决方法:
Locale locale = LocaleContextHolder.locale
DateTimeFormatter formatter
switch (type) {
case LocalTime:
formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(locale)
break
case LocalDate:
formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(locale)
break
default:
formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(locale)
}
return formatter
但它失败了Instant
类型。 Spock 重现规范:
def 'Instant locale formatting'() {
given:
Instant inst = Instant.ofEpochMilli(92554380000L)
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(UK)
expect:
formatter.format(inst) == "07/12/72 05:33"
}
该测试失败并出现错误:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfMonth
at java.time.Instant.getLong(Instant.java:603)
at java.time.format.DateTimePrintContext$1.getLong(DateTimePrintContext.java:205)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2543)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
at java.time.format.DateTimeFormatterBuilder$LocalizedPrinterParser.format(DateTimeFormatterBuilder.java:4350)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1744)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1718)
那么,为什么格式化程序无法格式化Instant
?
方法ofLocalizedDate()
, ofLocalizedTime()
and ofLocalizedDateTime()
提供本地化格式。
格式化Instant
需要时区。可以使用以下命令将其添加到格式化程序中withZone()
:
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(UK)
.withZone(ZoneId.systemDefault());
如果没有该区域,JSR-310 格式化程序就不知道如何将即时日期时间字段转换为人类日期时间字段。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)