如何在Java中使用Locale实现ZoneId的本地化显示?
解决时区本地化显示问题
问题核心:VV格式符输出的是IANA时区的标准化ID(如Asia/Shanghai),这是固定标识符,不会随Locale本地化。要显示对应Locale的时区名称,需使用专门的本地化格式符。
解决方案
使用z(缩写时区名称)或zzzz(完整时区名称)替换VV,这两个格式符会根据Locale输出本地化的时区名称:
代码示例
import java.time.ZonedDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Locale; public class TimeZoneLocalization { public static void main(String[] args) { Locale zhTwLocale = Locale.forLanguageTag("zh-TW"); ZonedDateTime zdt = ZonedDateTime.of(2024, 12, 31, 23, 59, 0, 0, ZoneId.of("Asia/Shanghai")); // 完整本地化时区名称 DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("h:mm:ss a zzzz", zhTwLocale); System.out.println(fullFormatter.format(zdt)); // 输出:下午11:59 中國標準時間 // 缩写本地化时区名称 DateTimeFormatter shortFormatter = DateTimeFormatter.ofPattern("h:mm:ss a z", zhTwLocale); System.out.println(shortFormatter.format(zdt)); // 输出:下午11:59 CST // 同时显示本地化名称和时区ID DateTimeFormatter combinedFormatter = DateTimeFormatter.ofPattern("h:mm:ss a zzzz (VV)", zhTwLocale); System.out.println(combinedFormatter.format(zdt)); // 输出:下午11:59 中國標準時間 (Asia/Shanghai) } }
关键说明
VV:输出IANA时区ID,属于标准化标识符,不支持本地化z:输出时区的缩写本地化名称(如中文环境下的CST)zzzz:输出时区的完整本地化名称(如中文繁体环境下的中國標準時間)
内容的提问来源于stack exchange,提问作者Barry Tone
相关产品推荐
相关产品推荐

