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

Java中如何将带毫秒的字符串转为保留毫秒信息的Date类型

问题解答:Date对象已保留毫秒,只是默认toString()不显示

你遇到的其实是个常见的认知误区:你的SysDateVar变量已经完整保留了毫秒信息,只是直接打印Date对象时,调用的是它默认的toString()方法,这个方法的输出格式不包含毫秒部分而已。

为什么会这样?

Date类内部是用一个long类型的时间戳来存储时间的(记录从1970-01-01 00:00:00 UTC开始的毫秒数),所以只要你解析字符串时正确读取了毫秒,这个值就会被存在Date对象里。你代码里的format.parse(curDate).getTime()返回的数值已经包含了那106毫秒,SysDateVar其实是带着毫秒信息的——只是默认打印看不到而已。

验证毫秒存在的方法

你可以在代码里加一行打印时间戳的代码,就能直观看到毫秒:

System.out.println("SysDateVar的时间戳(含毫秒):" + SysDateVar.getTime());

运行后会看到输出的数值末尾是106,这就证明毫秒确实被保留了。

要显示带毫秒的Date,该怎么做?

如果想在控制台输出带毫秒的时间,不能直接打印Date对象,而是要用你已经用到的SimpleDateFormat.format()方法来格式化输出,就像你处理abc变量那样。另外更推荐使用Java 8及以上版本的新日期时间API(java.time包),因为SimpleDateFormat是线程不安全的,新API设计更合理健壮。

改进你的原有代码

把打印SysDateVar的代码改成用format格式化输出即可:

// 替换原来的System.out.println("format.parse(curDate)="+ SysDateVar);
System.out.println("带毫秒的SysDateVar输出:" + format.format(SysDateVar));

这样就能得到和abc一样的带毫秒的输出结果。

Java 8+ 推荐写法

用LocalDateTime和DateTimeFormatter处理,代码更清晰且线程安全:

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

public class DateTimeExample {
    public static void main(String[] args) {
        String curDate = "20180510-10:50:58.106";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd-HH:mm:ss.SSS");
        
        // 解析成LocalDateTime(自带毫秒信息)
        LocalDateTime dateTime = LocalDateTime.parse(curDate, formatter);
        
        // 直接打印LocalDateTime会显示毫秒
        System.out.println("LocalDateTime输出:" + dateTime);
        // 或者用formatter格式化输出指定格式
        System.out.println("格式化输出:" + formatter.format(dateTime));
    }
}

运行输出:

LocalDateTime输出:2018-05-10T10:50:58.106
格式化输出:20180510-10:50:58.106

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:13:32