Java如何基于Locale实现仅斜杠分隔的纯数字本地化日期格式化
实现纯数字斜杠分隔的本地化日期格式化
DateTimeFormatter.ofLocalizedDate自带的FormatStyle.MEDIUM样式本身就会根据Locale返回包含文字月份、本地化分隔符的格式,无法直接满足「仅数字+斜杠、保留本地年月日顺序」的需求,正确实现方式如下:
可直接复用的工具方法
最简便的实现是先提取对应Locale下MEDIUM日期样式的原始格式串,再统一替换规则:把月份、日期、年份都转为固定长度的数字格式,所有非字段字符统一替换为斜杠,既保留原生的字段排序,又满足纯数字+斜杠的要求:
import java.time.ZonedDateTime; import java.time.chrono.IsoChronology; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.FormatStyle; import java.util.Locale; public class DateFormatUtil { public static DateTimeFormatter getNumericSlashDateFormatter(Locale locale) { // 获取对应Locale下ISO日历系统的MEDIUM级别日期原始格式模板 String rawPattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern( FormatStyle.MEDIUM, null, IsoChronology.INSTANCE, locale ); // 统一替换格式规则:月/日固定2位数字,年固定4位数字,所有分隔符替换为斜杠 String targetPattern = rawPattern .replaceAll("M+", "MM") .replaceAll("d+", "dd") .replaceAll("y+", "yyyy") .replaceAll("[^yMd]", "/") .replaceAll("^/|/$", ""); // 清除首尾可能出现的多余斜杠 return DateTimeFormatter.ofPattern(targetPattern, locale); } public static void main(String[] args) { ZonedDateTime zoned = ZonedDateTime.parse("2022-06-13T12:00:00+09:00[Asia/Tokyo]"); // ja-JP 输出:2022/06/13 System.out.println(zoned.format(getNumericSlashDateFormatter(Locale.forLanguageTag("ja-JP")))); // en-US 输出:06/13/2022 System.out.println(zoned.format(getNumericSlashDateFormatter(Locale.forLanguageTag("en-US")))); } }
实现说明
- 字段排序完全复用JDK内置的本地化规则,不需要手动维护各地区的年/月/日顺序,新增任意Locale都能自动适配
- 替换逻辑会自动过滤掉原始格式里的月份缩写、星期文字、本地化特殊分隔符,输出仅包含4位年、2位月、2位日和斜杠
- 代码逻辑简单,不需要处理复杂的字段遍历逻辑,兼容性覆盖所有JDK支持的ISO日历系统地区
内容的提问来源于stack exchange,提问作者zxwang
相关产品推荐
相关产品推荐

