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

Java中如何将LocalDateTime转换为保留两位毫秒的格式?

核心误区

LocalDateTime是时间存储对象,本身不携带任何格式信息。你直接打印该对象时调用的是其内置的toString()方法,输出规则固定:会输出到纳秒精度,自动去掉秒小数部分末尾的无效0。你现有逻辑是「格式化得到指定精度的字符串→再解析回LocalDateTime」,相当于只是修改了时间的精度,没有改变输出格式,自然达不到要求。


解决方案

场景1:仅需要输出/序列化时得到两位小数秒的字符串,不需要保留LocalDateTime类型

直接返回格式化后的字符串即可,无需再解析回LocalDateTime:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatUtils {
    private static final String ISO_DATE_TIME = "yyyy-MM-dd'T'HH:mm:ss.SS";
    // 把Formatter提为全局常量,避免重复创建
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(ISO_DATE_TIME);

    public static String formatToISO(final LocalDateTime localDateTime) {
        return FORMATTER.format(localDateTime);
    }

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        System.out.println(formatToISO(now));
    }
}

输出示例:

2021-11-30T11:48:28.449195200
2021-11-30T11:48:28.44

场景2:需要保留LocalDateTime类型,同时要求toString()输出两位小数秒

只需要把时间的纳秒精度截断到0.01秒(即10毫秒)即可,toString()会自动去掉末尾的0,输出两位小数:

import java.time.LocalDateTime;
import java.time.temporal.ChronoField;

public class DateTimeFormatUtils {
    public static LocalDateTime truncateTo2DecimalsOfSecond(LocalDateTime localDateTime) {
        // 取纳秒值,截断到0.01秒精度
        int nano = localDateTime.getNano();
        int truncatedNano = nano / 10_000_000 * 10_000_000;
        return localDateTime.with(ChronoField.NANO_OF_SECOND, truncatedNano);
    }

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        System.out.println(truncateTo2DecimalsOfSecond(now));
    }
}

输出示例:

2021-11-30T11:48:28.449195200
2021-11-30T11:48:28.44

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:54:02