Force 4-digit-year in localized strings generated from `DateTimeFormatter.ofLocalized…` in java.time(在 java.time 中从 `DateTimeFormatter.ofLocalized...` 生成的本地化字符串中强制使用 4 位数年份)
问题描述
DateTimeFormatter
java.time 中的类提供了三个 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 );
对于我所看到的语言环境,年份只有两位数,较短的 FormatStyle
样式.
For the locales I have seen, the year is only two digits in the shorter FormatStyle
styles.
如何让 java.time 本地化强制年份为四位数而不是两位?
How to let java.time localize yet force the years to be four digits rather than two?
我怀疑答案在于 DateTimeFormatterBuilder
类.但我找不到任何改变年份长度的功能.我还仔细阅读了 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.
这个问题类似于:
- 在 java 的 simpledateformat 中强制使用 4 位数年份
- Jodatime:如何打印 4 位数年份?
...但是这些问题针对的是现在被 java.time 类取代的旧日期时间框架.
…but those Questions are aimed at older date-time frameworks now supplanted by the java.time classes.
推荐答案
没有你想要的内置方法.但是,您可以应用以下解决方法:
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
这篇关于在 java.time 中从 `DateTimeFormatter.ofLocalized...` 生成的本地化字符串中强制使用 4 位数年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 java.time 中从 `DateTimeFormatter.ofLocalized...` 生成的


- 未找到/usr/local/lib 中的库 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 转换 ldap 日期 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 获取数字的最后一位 2022-01-01