如何将Joda-Time的DateTimeFormat.forStyle()转换为JSR 310 JavaTime?

sto*_*ito 1 migration jodatime java-8 java-time

我正在使用转换Grails Joda-Time插件到JavaTime.

我有这样的旧Joda时间码:

    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)
Run Code Online (Sandbox Code Playgroud)

我怎样才能将它转换为JSR 310?我找不到任何类似于接受样式的方法forStyle(String style).

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
Run Code Online (Sandbox Code Playgroud)

但它失败的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"
}
Run Code Online (Sandbox Code Playgroud)

此测试失败并出现错误:

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)
Run Code Online (Sandbox Code Playgroud)

那么,为什么格式化程序无法格式化Instant

Jod*_*hen 5

方法ofLocalizedDate(),ofLocalizedTime()ofLocalizedDateTime()提供本地化格式.

要格式化Instant时区是必需的.这可以使用以下命令添加到格式化程序withZone():

DateTimeFormatter formatter =
    DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
                     .withLocale(UK)
                     .withZone(ZoneId.systemDefault());
Run Code Online (Sandbox Code Playgroud)

没有区域,JSR-310格式化器不知道如何将瞬时转换为人类日期时间字段.