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

Java如何将毫秒时间戳字符串转换为Date类型完成日期格式化

问题根因
  • 你遇到的解析报错本质是时间字符串格式不统一:1654653731536是标准毫秒级Unix时间戳字符串,和你定义的dd-MM-yyyy HH:mm:ss日期格式完全不匹配,直接用对应规则的SimpleDateFormat解析必然失败。
  • 读取Excel单元格时直接调用getStringCellValue()没有做类型校验:如果单元格存的是数值类型的时间/时间戳,该方法会直接返回纯数字字符串,不会自动做日期格式转换。
具体修复方案

1. 毫秒时间戳字符串转Date

毫秒时间戳是从1970-01-01 00:00:00 UTC起算的毫秒计数,直接将字符串转为long类型后传入Date构造方法即可得到对应Date对象:

// 转换示例
String timestampStr = "1654653731536";
Date dateFromTimestamp = new Date(Long.parseLong(timestampStr));

2. 指定格式的日期字符串转Date

你已经定义了对应格式的SimpleDateFormat实例,直接调用parse方法即可解析格式化后的日期字符串,注意需要捕获解析异常:

String formattedDateStr = "07-06-2022 21:02:12";
Date dateFromFormattedStr = null;
try {
    dateFromFormattedStr = sdf.parse(formattedDateStr);
} catch (ParseException e) {
    e.printStackTrace();
    // 此处可添加解析失败的业务兜底逻辑,比如抛出异常、记录错误日志
}

3. 兼容两种格式的通用转换逻辑

由于你现在存储的时间同时存在时间戳、格式化字符串两种格式,可以先判断字符串类型再选择转换方式,避免解析报错:

private Date parseTimeStrToDate(String timeStr) throws ParseException {
    // 纯数字字符串判定为时间戳
    if (timeStr.matches("^\\d+$")) {
        return new Date(Long.parseLong(timeStr));
    }
    // 其余情况按你定义的日期格式解析
    return sdf.parse(timeStr);
}

在调用calcTimeWorked前,先把起止时间都通过这个方法转为Date对象,再传入计算逻辑即可。

4. 优化Excel读取逻辑从根源避免格式混乱

不要直接调用getStringCellValue()读取时间类单元格,先判断单元格类型再取值,统一输出格式:

private String getExcelTimeCellValue(Cell cell) {
    if (cell == null) {
        return "";
    }
    CellType cellType = cell.getCellType();
    if (cellType == CellType.NUMERIC) {
        // 是Excel内置日期格式
        if (DateUtil.isCellDateFormatted(cell)) {
            return sdf.format(cell.getDateCellValue());
        }
        // 是数值型时间戳
        return String.valueOf((long) cell.getNumericCellValue());
    }
    return cell.getStringCellValue();
}

替换你原有updatePunchHistory方法里直接调用getStringCellValue()读时间单元格的逻辑,就能从读取环节保证时间格式可识别。

补充提示:如果你的项目使用Java 8及以上版本,更推荐替换为java.time包下的LocalDateTime、DateTimeFormatter类,相比老旧的Date、SimpleDateFormat线程安全性更好,API设计也更简洁,能避免多线程场景下的解析异常问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 22:31:01