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

使用SimpleDateFormat报错:Cannot format given Object as a Date的原因与解决

问题原因与解决方案

原因

SimpleDateFormat.format()方法要求传入的参数是Date类型(或其子类),你直接传入了字符串"2022-12-07T10:57:23.970Z",方法无法将字符串对象直接格式化为日期,因此抛出Cannot format given Object as a Date异常。

另外需要注意:你定义的格式"yyyy-MM-dd'T'HH:mm:ss.SSSZ"中的Z代表时区偏移量(如+0800),但输入字符串里的Z是UTC时间的标记符,属于字面量,这会导致后续解析字符串为Date时也出错。

解决方法

方法一:修复原有SimpleDateFormat代码

先通过parse()方法将字符串解析为Date对象,再调用format()方法。同时要修正格式字符串,把字面量Z用单引号包裹:

private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

public static void main(String[] args) throws ParseException {
    // 先将字符串解析为Date对象
    Date date = SIMPLE_DATE_FORMAT.parse("2022-12-07T10:57:23.970Z");
    // 再格式化Date对象
    final String format = SIMPLE_DATE_FORMAT.format(date);
    System.out.println(format);
}

方法二:使用Java 8+推荐的日期API(更安全可靠)

SimpleDateFormat存在线程不安全的问题,Java 8及以上版本推荐使用java.time包下的日期类,示例如下:

import java.time.Instant;
import java.time.format.DateTimeFormatter;

public class DateDemo {
    // ISO-8601标准格式,适配输入的字符串格式
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_INSTANT;

    public static void main(String[] args) {
        // 直接解析字符串为Instant对象
        Instant instant = Instant.parse("2022-12-07T10:57:23.970Z");
        // 格式化输出
        String format = FORMATTER.format(instant);
        System.out.println(format);
    }
}

如果需要自定义格式,可以使用OffsetDateTime配合自定义格式化器:

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

public class DateDemo {
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");

    public static void main(String[] args) {
        OffsetDateTime dateTime = OffsetDateTime.parse("2022-12-07T10:57:23.970Z");
        String format = FORMATTER.format(dateTime);
        System.out.println(format);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:50:21