在java.time中从`MonthDay`或`YearMonth`类本地化字符串?
Java 8及更高版本中内置的java.time类提供MonthDay
和YearMonth
类。 他们的toString
和parse
方法使用标准的ISO 8601格式( YYYY-MM
--MM-DD
和YYYY-MM
),这是明智的。
对于向人类呈现,标准格式可能不合适。 反正是否有生成自动本地化的字符串来表示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
时抛出exception。
对于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)
见JDK-8168532 。 JDK需要增强才能轻松实现。
可以在JDK之外完成工作,但这是很多工作。 您必须解析CLDR XML文件(它们是相互链接的并且有许多引用)。 然后,您为MonthYear
和YearMonth
提取相关的本地化模式,然后可以使用这些模式创建DateTimeFormatter
。
或者,您可以根据业务需要对Map
进行硬编码 – Map
。