如何使用DateTimeFormatter.ofPattern()获取完整月份名称
问题原因
你遇到的是Java法语区域日期格式化的默认样式偏好问题:部分JDK版本默认使用内置的区域语言数据,法语环境下MMMM格式符会默认返回缩写形式的月份文本,而非你期望的全写。
解决方法
方案1:显式强制指定全写月份格式
通过DateTimeFormatterBuilder手动指定月份字段使用全写风格,同时明确指定法语区域,避免受系统默认区域影响:
import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.TextStyle; import java.time.temporal.ChronoField; import java.util.Locale; // 明确指定法语区域,可根据需要替换为Locale.CANADA_FRENCH等其他法语变体 Locale frenchLocale = Locale.FRANCE; DateTimeFormatter fullMonthFormatter = new DateTimeFormatterBuilder() .appendPattern("dd ") // 强制使用完整月份名称 .appendText(ChronoField.MONTH_OF_YEAR, TextStyle.FULL) .appendPattern(" uuuu") .toFormatter(frenchLocale); String dateActuelle = fullMonthFormatter.format(LocalDate.now());
运行后即可输出你期望的06 septembre 2021格式。
方案2:修改区域数据提供器(适配JDK8场景)
如果你使用的是JDK8,默认使用JRE内置的区域数据,法语月份全写规则不符合预期,可以在JVM启动参数中添加以下配置,切换为CLDR通用区域数据:
-Djava.locale.providers=CLDR
添加后你原来的代码只要补充指定法语区域,也可以正常输出全写月份:
String dateActuelle = DateTimeFormatter.ofPattern("dd MMMM uuuu", Locale.FRANCE).format(LocalDate.now());
内容的提问来源于stack exchange,提问作者LordHorus
相关产品推荐
相关产品推荐

