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

Java 11中如何用ZonedDateTime输出指定格式的日期时间?

Java 11中ZonedDateTime保留三位小数秒的格式化方法

默认的DateTimeFormatter.ISO_LOCAL_DATE_TIME会输出可变长度的纳秒部分(最多9位),要得到仅保留三位小数秒的格式,有两种简洁的实现方式:

方法一:自定义格式化模式

直接指定包含三位小数秒的格式字符串:

ZonedDateTime zdt = ZonedDateTime.now();
// 定义格式:年-月-日T时:分:秒.三位小数秒
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
String result = zdt.format(customFormatter);
// 输出示例:2023-11-16T09:54:12.123

方法二:基于ISO格式修改小数秒位数

Java 9及以上支持直接为ISO格式指定小数秒的固定位数,Java 11完全兼容:

ZonedDateTime zdt = ZonedDateTime.now();
// 复用ISO_LOCAL_DATE_TIME格式,仅将小数秒固定为3位
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME.withFractionalSeconds(3);
String result = zdt.format(formatter);
// 输出示例:2023-11-16T09:54:12.123

两种方法都能满足需求,第二种更贴合标准ISO格式的定义,推荐优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 01:44:52