You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用FormatStyle.MEDIUM格式化带时区的ZonedDateTime获得可读结果

解决方案

完全可以实现你需要的格式化效果,常用有两种实现方案:

方案1:硬编码匹配FormatStyle.MEDIUM风格的模式

直接自定义格式化模式,末尾加时区字段即可,代码示例如下:

LocalDateTime localDateTime = LocalDateTime.now();
// 转换为带时区的ZonedDateTime
ZonedDateTime zdt = localDateTime.atZone(ZoneId.of("America/New_York"));
// 模式中:MMM d, yyyy h:mm:ss a 对应MEDIUM风格的日期时间格式,z表示短时区名称
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d, yyyy h:mm:ss a z", Locale.US);
System.out.println(zdt.format(formatter));

运行上述代码即可输出Oct 20, 2021 1:00:02 PM EST的效果。
如果不希望使用EST这类非标准化的短时区名,只需要把模式里的z替换为VV,输出就会变为Oct 20, 2021 1:00:02 PM America/New_York,更符合生产环境的规范要求。

方案2:动态适配本地化格式(推荐多语言场景)

如果需要适配不同语言环境的MEDIUM格式(比如中文环境下自动展示为2021年10月20日 下午1:00:02的格式),不需要硬编码日期格式,可以通过DateTimeFormatterBuilder动态拼接时区字段:

LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zdt = localDateTime.atZone(ZoneId.of("America/New_York"));
// 动态获取当前语言环境下MEDIUM风格的日期时间格式
String localizedPattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
        FormatStyle.MEDIUM,
        FormatStyle.MEDIUM,
        IsoChronology.INSTANCE,
        Locale.getDefault()
);
// 拼接时区字段
String patternWithZone = localizedPattern + " z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(patternWithZone);
System.out.println(zdt.format(formatter));

内容的提问来源于stack exchange,提问作者Woodchuck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 03:48:00