Bas*_*que 4 java localization 2-digit-year java-time
DateTimeFormatterjava.time中的类提供了三种ofLocalized…生成字符串的方法,以表示包含一年的值.例如,ofLocalizedDate.
Locale l = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( l );
LocalDate today = LocalDate.now( ZoneId.of( "America/Chicago" ) );
String output = today.format( f );
Run Code Online (Sandbox Code Playgroud)
对于我看过的语言环境,年份只是较短FormatStyle样式的两位数.
如何让java.time本地化却迫使年份变为四位数而不是两位数?
我怀疑答案在DateTimeFormatterBuilder课堂上.但我找不到任何改变一年的长度的功能.我也仔细阅读了Java 9源代码,但是不能很好地解释代码以找到答案.
这个问题类似于:
...但是这些问题针对的是现在由java.time类取代的旧日期时间框架.
没有内置的方法可以满足您的需求.但是,您可以应用以下解决方法:
Locale locale = Locale.ENGLISH;
String shortPattern =
DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT,
null,
IsoChronology.INSTANCE,
locale
);
System.out.println(shortPattern); // M/d/yy
if (shortPattern.contains("yy") && !shortPattern.contains("yyy")) {
shortPattern = shortPattern.replace("yy", "yyyy");
}
System.out.println(shortPattern); // M/d/yyyy
DateTimeFormatter shortStyleFormatter = DateTimeFormatter.ofPattern(shortPattern, locale);
LocalDate today = LocalDate.now(ZoneId.of("America/Chicago"));
String output = today.format(shortStyleFormatter);
System.out.println(output); // 11/29/2016
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
399 次 |
| 最近记录: |