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

使用SimpleDateFormat进行日期时间比较结果异常,求排查原因

问题解析与解决方案

哦,这个坑我之前也踩过!你遇到的问题根源是SimpleDateFormat的时间格式符用错了😅

问题原因

你代码里用的hh是12小时制的格式符(范围是1-12),而且当你没有指定AM/PM标记时,SimpleDateFormat会默认把时间解析为上午(AM)。这就导致:

  • 5/31/2018 12:07被解析成当天凌晨00:07(12 AM)
  • 5/31/2018 11:49被解析成当天上午11:49(11 AM)

显然上午11:49在凌晨00:07之后,所以after()方法返回true,这就是不符合你预期的原因。

而当你改成13:00时,12小时制无法直接解析13,它会自动将其转换为下午1点(1 PM),也就是13:00,这时候上午11:49确实在13:00之前,所以after()返回false,结果就正确了。

解决方案

把格式符从hh改成HH(24小时制,范围是00-23),这样就能正确解析所有00-23的时间了:

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm");
System.out.println(format.parse("5/31/2018 11:49").after(format.parse("5/31/2018 12:07")));

运行这段代码,输出就是你预期的false。

额外推荐(更安全的写法)

如果你使用的是Java 8及以上版本,非常建议用java.time包下的类(比如LocalDateTime、DateTimeFormatter)来处理时间,它们是线程安全且设计更合理的,避免了SimpleDateFormat的各种坑:

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

public class TimeCompare {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm");
        LocalDateTime time1 = LocalDateTime.parse("5/31/2018 11:49", formatter);
        LocalDateTime time2 = LocalDateTime.parse("5/31/2018 12:07", formatter);
        System.out.println(time1.isAfter(time2)); // 输出false
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:05:21