問題描述
DateTimeFormatter
java.time 中的類提供了三個(gè) ofLocalized…
方法來生成字符串來表示包含年份的值.例如,ofLocalizedDate
.
The DateTimeFormatter
class in java.time offers three ofLocalized…
methods for generating strings to represent values that include a year. For example, 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 );
對于我所看到的語言環(huán)境,年份只有兩位數(shù),較短的 FormatStyle
樣式.
For the locales I have seen, the year is only two digits in the shorter FormatStyle
styles.
如何讓 java.time 本地化強(qiáng)制年份為四位數(shù)而不是兩位?
How to let java.time localize yet force the years to be four digits rather than two?
我懷疑答案在于 DateTimeFormatterBuilder
類.但我找不到任何改變年份長度的功能.我還仔細(xì)閱讀了 Java 9 源代碼,但無法很好地挖掘該代碼以找到答案.
I suspect the Answer lies in DateTimeFormatterBuilder
class. 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.
這個(gè)問題類似于:
- 在 java 的 simpledateformat 中強(qiáng)制使用 4 位數(shù)年份
- Jodatime:如何打印 4 位數(shù)年份?
...但是這些問題針對的是現(xiàn)在被 java.time 類取代的舊日期時(shí)間框架.
…but those Questions are aimed at older date-time frameworks now supplanted by the java.time classes.
推薦答案
沒有你想要的內(nèi)置方法.但是,您可以應(yīng)用以下解決方法:
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
這篇關(guān)于在 java.time 中從 `DateTimeFormatter.ofLocalized...` 生成的本地化字符串中強(qiáng)制使用 4 位數(shù)年份的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!