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

Java GMT日期格式化问题:如何将时区转为GMT-00:00

解决方案:将日期输出为UTC时区格式

问题说明

Date对象本身仅存储时间戳(从1970-01-01 UTC开始的毫秒数),不包含时区信息。控制台打印或格式化时默认使用本地时区,这就是你输出GMT-03:00的原因。要输出GMT-00:00(即UTC时区),需要在格式化时指定时区为UTC。


方案1:使用传统SimpleDateFormat

修正你的代码,给格式化器设置UTC时区:

// 初始化解析用的格式化器,指定UTC时区
SimpleDateFormat parserSdf = new SimpleDateFormat("yyyyMMdd");
parserSdf.setTimeZone(TimeZone.getTimeZone("UTC"));

// 解析日期字符串
Date date = parserSdf.parse(params.date);

// 初始化输出用的格式化器,指定UTC时区和输出格式
SimpleDateFormat outputSdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
outputSdf.setTimeZone(TimeZone.getTimeZone("UTC"));

// 输出结果
System.out.println(outputSdf.format(date));

注意:SimpleDateFormat是非线程安全的,如果在多线程环境下使用需额外处理。


方案2:Java 8+ 推荐使用java.time API

Java 8引入的新日期时间API线程安全、设计更严谨,建议替代旧API:

// 解析字符串为LocalDate(BASIC_ISO_DATE对应"yyyyMMdd"格式)
LocalDate localDate = LocalDate.parse(params.date, DateTimeFormatter.BASIC_ISO_DATE);

// 拼接时间并转换为UTC时区的时间(这里设置为21:00:00,匹配你的示例输出)
ZonedDateTime utcDateTime = localDate.atTime(21, 0).atZone(ZoneOffset.UTC);

// 定义输出格式并打印
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
System.out.println(formatter.format(utcDateTime));

内容的提问来源于stack exchange,提问作者Gustavo Silva Costa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:21:29