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

计算时间差结果错误,日期比较时天数统计异常技术求助

问题排查与解决方案

我一眼就揪出了问题的核心——你在SimpleDateFormat的格式字符串里用错了占位符!

错误根源

你写的格式代码是:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm/dd/yyyy HH:mm:ss");

这里的小写mm代表的是分钟,而不是月份!月份的正确占位符是大写的MM。这就导致解析"08/22/2018 20:56:03"时,程序会把08当成分钟数,而不是8月,直接把整个日期解析得面目全非,后续计算时间差、统计天数自然全是错误结果。

修正后的代码

把格式字符串里的mm改成MM就解决了核心问题,我帮你补全并修正了代码:

final String myDate = "08/22/2018 20:56:03"; 
// 注意:月份用大写MM,分钟用小写mm
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
System.out.println("timeeeeeeeeeeeee" + "-" + simpleDateFormat); 
Date date = null; 
try { 
    date = simpleDateFormat.parse(myDate); 
} catch (ParseException e) { 
    e.printStackTrace(); 
} 
long endtime = date.getTime(); 
Date d = null; 
try { 
    // 补全你未写完的获取当前日期并解析的逻辑
    d = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
    // 计算时间差(转换为天数)
    long diffMs = Math.abs(endtime - d.getTime());
    long diffDays = diffMs / (1000 * 60 * 60 * 24);
    System.out.println("日期天数差:" + diffDays);
} catch (ParseException e) { 
    e.printStackTrace(); 
}

额外优化建议

另外,SimpleDateFormat是线程不安全的类,如果是在多线程场景下使用,建议换成Java 8+引入的java.time包下的API(比如DateTimeFormatter、LocalDateTime),这些类天生线程安全,API设计也更清晰直观:

final String myDate = "08/22/2018 20:56:03";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
LocalDateTime targetDateTime = LocalDateTime.parse(myDate, formatter);
LocalDateTime currentDateTime = LocalDateTime.now();
// 直接计算天数差
long diffInDays = ChronoUnit.DAYS.between(targetDateTime, currentDateTime);
System.out.println("日期天数差:" + Math.abs(diffInDays));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:53:55