简体   繁体   English

强制从java.time中的`DateTimeFormatter.ofLocalized ...`生成的本地化字符串中的4位数年份

[英]Force 4-digit-year in localized strings generated from `DateTimeFormatter.ofLocalized…` in java.time

The DateTimeFormatter class in java.time offers three ofLocalized… methods for generating strings to represent values that include a year. java.time中的DateTimeFormatter类提供了三种ofLocalized…方法,用于生成表示包含一年的值的字符串。 For example, ofLocalizedDate . 例如, 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 );

For the locales I have seen, the year is only two digits in the shorter FormatStyle styles. 对于我看过的语言环境,年份只是较短的FormatStyle样式中的两位数。

How to let java.time localize yet force the years to be four digits rather than two? 如何让java.time本地化却迫使年份变为四位数而不是两位数

I suspect the Answer lies in DateTimeFormatterBuilder class. 我怀疑答案在于DateTimeFormatterBuilder类。 But I cannot find any feature alter the length of year. 但我找不到任何改变一年的长度的功能。 I also perused the Java 9 source code , but cannot spelunk that code well enough to find an answer. 我也仔细阅读了Java 9源代码 ,但是不能很好地解释代码以找到答案。

This Question is similar to: 这个问题类似于:

…but those Questions are aimed at older date-time frameworks now supplanted by the java.time classes. ...但是这些问题针对的是现在由java.time类取代的旧日期时间框架。

There is no built-in method for what you want. 没有内置的方法可以满足您的需求。 However, you could apply following workaround: 但是,您可以应用以下解决方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM