如何不改变时间值切换时区?UTC时间格式化问题求助
解决UTC时间格式化时区显示错误的问题
这个问题我之前也碰到过,其实核心是没搞清楚SimpleDateFormat的时区作用时机——它不仅影响格式化显示,还会影响解析时的时间点转换!你之前的操作要么没指定时区导致用了默认的EST,要么只在格式化时指定UTC,但解析时用了默认时区,导致时间点被转换,自然输出不符合预期。
用旧API(SimpleDateFormat)的正确做法
要确保解析和格式化两个步骤都明确指定UTC时区,这样才能保证时间点正确,同时输出UTC时区标识:
import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class UtcFormatExample { public static void main(String[] args) throws Exception { // 你的原始UTC时间字符串 String utcTimestamp = "2018-01-01 18:20:23.11"; // 第一步:解析UTC字符串时,指定时区为UTC,得到正确的时间点 SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS"); parser.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = parser.parse(utcTimestamp); // 第二步:格式化时同样指定UTC时区,输出你要的格式 SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy kk:mm z"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); String formattedResult = formatter.format(date); System.out.println(formattedResult); // 输出:01 Jan 2018 18:20 UTC } }
为什么之前会出错?如果解析时没指定UTC,SimpleDateFormat会用你本地的EST时区去解析这个UTC字符串,导致Date对象对应的时间点其实是2018-01-01 18:20 UTC转换成EST的时间,之后再转成UTC格式化,时间自然就偏移了。
推荐用Java 8+的java.time API(更可靠)
SimpleDateFormat是线程不安全的,而且旧的日期API设计有很多缺陷,Java 8之后的java.time API更清晰、更可靠,推荐使用:
import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.ZoneId; public class ModernUtcFormatExample { public static void main(String[] args) { String utcTimestamp = "2018-01-01 18:20:23.11"; // 定义解析器,绑定UTC时区 DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS") .withZone(ZoneId.of("UTC")); // 解析得到带UTC时区的时间对象 ZonedDateTime utcZonedTime = ZonedDateTime.parse(utcTimestamp, parser); // 定义格式化器,直接格式化输出 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy kk:mm z"); String formattedResult = formatter.format(utcZonedTime); System.out.println(formattedResult); // 输出:01 Jan 2018 18:20 UTC } }
这里ZonedDateTime直接绑定了UTC时区,格式化时自然会输出UTC标识,完全不用担心时区转换的问题,代码逻辑也更直观。
内容的提问来源于stack exchange,提问作者San Kay
相关产品推荐
相关产品推荐

