Java 8 和更高版本中内置的 java.time 类提供MonthDay
和YearMonth
类。他们toString
和parse
方法使用标准ISO 8601格式 ( --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
。
对于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)