2014-12-12 1 views
1

Я работаю над конвертированием плагинов Grails Joda-Time в JavaTime.Как скрывать JTime DateTimeFormat.forStyle() в JSR 310 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) 

Как я могу CONVER его 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 

Но он не из Instant типа. Спок спецификации воспроизвести:

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?

ответ

4

Методы ofLocalizedDate(), ofLocalizedTime() и ofLocalizedDateTime() обеспечивают локализованные форматы ,

Для форматирования Instant требуется зона времени. Это может быть добавлено к форматеру с помощью withZone():

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

Без зоны, JSR-310 форматировщик не имеет сведений о том, как преобразовать в тот момент, на поля даты и время человека.

+1

Я нашел странную проблему, возможно ошибку http://stackoverflow.com/questions/27488494/how-to-parse-string-with-date-but-without-time-in-local-format-to -zoneddatetime – stokito

1

JSR 310 имеет другие способы замены стиля: DateTimeFormatter.ofLocalizedTime(), DateTimeFormatter.ofLocalizedDate() и DateTimeFormatter.ofLocalizedDateTime()

Другая проблема заключается в том, что Instant тип не может быть отформатирован Format Instant to String