Java中移除ZonedDateTime的[UTC]时区后缀,保留Z格式
保留ZonedDateTime类型,输出不带时区标识的UTC格式时间
问题场景
我将毫秒值转换为ZonedDateTime类型,代码如下:
Long lEpochMilliSeconds = 1668415926445; System.out.println(ZonedDateTime.ofInstant(Instant.ofEpochMilli(lEpochMilliSeconds),ZoneId.of("UTC")));
当前输出会附带时区标识:
2022-10-28T12:59:34.939Z[UTC]
我需要输出格式为:
2022-10-28T12:59:34.939Z
并且必须保持ZonedDateTime类型,不能转为字符串用于后续逻辑。
解决方案
问题出在ZonedDateTime默认的toString()方法会额外输出时区ID。我们只需要在输出阶段使用DateTimeFormatter指定格式即可,无需修改ZonedDateTime实例本身,这样既能保留原类型,又能得到期望的输出格式。
方法一:使用内置的ISO_INSTANT格式化器
Long lEpochMilliSeconds = 1668415926445; ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(lEpochMilliSeconds), ZoneId.of("UTC")); // 使用ISO_INSTANT格式输出,匹配期望的格式 System.out.println(DateTimeFormatter.ISO_INSTANT.format(zonedDateTime));
方法二:自定义格式化器
如果需要更灵活的格式控制,可以自定义格式化规则:
Long lEpochMilliSeconds = 1668415926445; ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(lEpochMilliSeconds), ZoneId.of("UTC")); // 自定义格式,X表示时区偏移(UTC下为Z) DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX") .withZone(ZoneId.of("UTC")); System.out.println(customFormatter.format(zonedDateTime));
关键说明
- ZonedDateTime实例全程保持原类型,后续逻辑可以直接使用该对象
- 仅在输出时通过格式化器处理字符串展示,不改变对象本身的类型和数据
内容的提问来源于stack exchange,提问作者Sai T
相关产品推荐
相关产品推荐

