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

Java 8 DateTimeParseException求助:字符串转时间戳解析失败

解决DateTimeFormatter解析字符串为时间戳的异常问题

嘿,我来帮你搞定这个解析异常的问题~你这段代码的核心问题是直接用DateTimeFormatter.parse()的返回值拼接字符串,而且没有把解析结果转换成明确的日期时间类型,导致解析过程中抛出了异常。

为啥会抛异常?

DateTimeFormatter.parse()默认返回的是TemporalAccessor,这是个通用的时间访问接口,没有明确的日期时间类型信息。JDK在解析时如果没有明确的目标类型,就可能无法正确识别字符串对应的时间结构,从而抛出DateTimeParseException。

修正后的代码

下面是能正确解析并生成时间戳的代码:

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

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        // 先解析为明确的LocalDateTime类型
        LocalDateTime dateTime = LocalDateTime.parse("20180301050630663", formatter);
        // 转换为带时区的时间,再转成Instant获取时间戳(这里用系统默认时区,可按需修改)
        long timestamp = dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        System.out.println("Timestamp:" + timestamp);
    }
}

几个关键点要注意:

  • 明确解析类型:用LocalDateTime.parse()直接把字符串解析成具体的日期时间对象,避免TemporalAccessor的模糊性,这就能解决你遇到的解析异常。
  • 时区处理:LocalDateTime不含时区信息,要转成时间戳(基于UTC的Instant)必须指定时区——你可以用系统默认时区,也可以指定像ZoneId.of("UTC")这样的固定时区。
  • 时间戳精度:如果需要秒级时间戳,把toEpochMilli()换成toEpochSecond()就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:18:41