2017-01-25 6 views
1

Классы java.time, встроенные в Java 8 и более поздние версии, предлагают классы MonthDay и YearMonth. Их методы toString и parse используют стандартные форматы ISO 8601 (--MM-DD & YYYY-MM), что является мудрым.Локализовать строку из классов MonthDay или YearMonth в java.time?

Для представления людям обычные форматы могут быть непригодными. Нужно ли вообще генерировать автоматически локализованную строку для представления значений в объектах MonthDay или YearMonth?

Например, в Соединенных Штатах Америки обычно может потребоваться MM/DD для месяца и MM/YY за год-месяц. В то время как в Великобритании пользователям может понадобиться DD/MM для месяца.

В любом случае, чтобы автоматизировать такие варианты на Locale, а не явно определять шаблоны форматирования?


Я пробовал следующий код, используя ориентированный на даты форматтера.

Locale l = Locale.US; 
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate (FormatStyle.SHORT).withLocale (l); 

YearMonth ym = YearMonth.of (2017 , Month.JANUARY); 
MonthDay md = MonthDay.of (Month.JANUARY , 29); 

String outputYm = ym.format (f); 
String outputMd = md.format (f); 

Этот код не удается, бросает исключение, когда используется либо для YearMonth или MonthDay.

Для YearMonth:

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfMonth 
    at java.time.YearMonth.getLong(YearMonth.java:494) 
    at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298) 
    at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2540) 
    at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179) 
    at java.time.format.DateTimeFormatterBuilder$LocalizedPrinterParser.format(DateTimeFormatterBuilder.java:4347) 
    at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179) 
    at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746) 
    at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720) 
    at java.time.YearMonth.format(YearMonth.java:1073) 
    at javatimestuff.App.doIt(App.java:56) 
    at javatimestuff.App.main(App.java:45) 

MonthDay Для:

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra 
    at java.time.MonthDay.getLong(MonthDay.java:451) 
    at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298) 
    at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2540) 
    at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179) 
    at java.time.format.DateTimeFormatterBuilder$LocalizedPrinterParser.format(DateTimeFormatterBuilder.java:4347) 
    at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179) 
    at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746) 
    at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720) 
    at java.time.MonthDay.format(MonthDay.java:646) 
    at javatimestuff.App.doIt(App.java:57) 
    at javatimestuff.App.main(App.java:45) 
+0

Предположительно, вы ищете что-то, что связано с 'MonthDay.format (DateTimeFormatter)'? –

+0

@LouisWasserman Добавлен код, показывающий, что 'DateTimeFormatter.ofLocalizedDate' терпит неудачу в методах' format() 'как' MonthDay', так и 'YearMonth'. Если у вас есть вариант, который работает, отправьте сообщение. Интересно, может ли ответ быть в ['DateTimeFormatterBuilder'] (https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatterBuilder.html), но я не знаю, как это сделать. –

ответ

2

См JDK-8168532. В JDK требуется усовершенствование, чтобы сделать это легко.

Возможно работать за пределами JDK, но это очень много работы. Вы должны разбирать XML-файлы CLDR (которые взаимосвязаны и имеют много ссылок). Затем вы извлекаете соответствующие локализованные шаблоны для MonthYear и YearMonth. Затем эти шаблоны можно использовать для создания DateTimeFormatter.

В качестве альтернативы, вы можете жестко скопировать карту - Map<Locale, DateTimeFormatter> - исходя из ваших потребностей бизнеса.

+0

Насколько вероятны шансы, что JDK-8168532 будет исправлен в Java 10? – mkurz

Смежные вопросы