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

如何将BigInteger值转换为yyyy-mm-dd hh:ss:mmm格式的日期时间?

问题分析与解决方案

你的代码核心错误是把日期拼接的数字直接当作时间戳传入Date构造函数——Date的构造参数是从1970-01-01 00:00:00 GMT开始的毫秒数,而你的数值是年、月、日、时、分、秒、毫秒的拼接值,两者完全不是一回事。另外,你用的SimpleDateFormat和Date类已经过时,建议使用Java 8+引入的java.time系列API,更可靠且线程安全。

正确实现代码

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

public class DateConversion {
    public static void main(String[] args) {
        BigInteger sum = new BigInteger("2023062223380346");
        String dateStr = sum.toString();
        
        // 注意:你的输入值是16位,而目标毫秒是3位,这里补零补全为17位(若实际输入是17位可跳过此步骤)
        if (dateStr.length() == 16) {
            dateStr += "0"; // 若预期是466毫秒,输入值应为"20230622233803466"(17位)
        }
        
        // 定义解析格式:对应输入的数字结构yyyyMMddHHmmssSSS
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        LocalDateTime dateTime = LocalDateTime.parse(dateStr, parser);
        
        // 定义输出格式:yyyy-MM-dd HH:mm:ss:SSS
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");
        String formattedDate = dateTime.format(formatter);
        
        System.out.println(formattedDate);
    }
}

关键说明

  • 先把BigInteger转为字符串,确保长度符合yyyyMMddHHmmssSSS的格式要求(17位,其中毫秒占3位)。如果你的实际输入就是17位的20230622233803466,可以直接去掉补零的逻辑。
  • 使用LocalDateTime处理无时区的日期时间,若需要指定时区,可改用ZonedDateTime配合时区信息。
  • DateTimeFormatter是线程安全的,比SimpleDateFormat更适合在多线程环境使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:57:14