Java 日期时间比较给出的结果不正确
由于11:49早于12:07,此代码应给出false。但代码正在返回真值 如果我把12:07改为13:00,它会给出false,这是正确的。我不知道12:07有什么问题。我错过什么了吗?我也尝试了比较法和给定时间法,结果相同Java 日期时间比较给出的结果不正确,java,date,datetime,simpledateformat,date-comparison,Java,Date,Datetime,Simpledateformat,Date Comparison,由于11:49早于12:07,此代码应给出false。但代码正在返回真值 如果我把12:07改为13:00,它会给出false,这是正确的。我不知道12:07有什么问题。我错过什么了吗?我也尝试了比较法和给定时间法,结果相同 SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm"); System.out.println(format.parse("5/31/2018 11:49").after(format.parse
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")));
hh
(范围1-12),12:07
解析为00:07
:
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm");
System.out.println(format.parse("5/31/2018 00:07").equals(format.parse("5/31/2018 12:07"))); // true
改用HH
(范围0-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
“hh”是一个12小时的时钟,因此“12:07”在中被解释为“12:07 AM”。你可能想要“HH”。请参见格式中缺少某些内容 hh格式为小时,以上午/下午(1-12)为单位,如文档中所示: 如果运行以下命令:
System.out.println(format.parse("5/31/2018 12:07"));
您将获得:
Thu May 31 00:07:00 ART 2018
这就是为什么你会成为现实
您应该将时间格式更改为:HH:mm。这就足够了。除了其他答案之外,您还可以通过在
SimpleDataFormat
对象上调用setLenient(false)
来更容易发现这些隐藏的问题
默认情况下,解析过程是宽松的,即解析成功,即使字符串
与模式不完全匹配
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm");
format.setLenient(false);
// Next line will throw a ParseException, as the second call to parse now fails
System.out.println(format.parse("5/31/2018 11:49").after(format.parse("5/31/2018 13:07")));
你写道,在小时部分写“13”很好,增加了你的困惑。将lenient设置为false
,parse
将抛出ParseException
,因为“13”与“hh”不匹配,这使得字符串与模式不匹配变得更加明显
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm");
format.setLenient(false);
// Next line will throw a ParseException, as the second call to parse now fails
System.out.println(format.parse("5/31/2018 11:49").after(format.parse("5/31/2018 13:07")));
我猜12:07是凌晨12:07,就在午夜七分钟后。您必须指定AM或PM,或者找到其他方法告诉系统某些日期将假定为PM。我建议您避免使用SimpleDateFormat
类。它不仅早已过时,而且还出了名的麻烦。今天,我们有了更好的解决方案。它在您尝试解析13:07
时抛出了ParseException
(而不是NullPointerException
),但在12:07
的情况下就不是问题中提到的那样了。因此,即使有一点小小的改善,这也不是真正的重点。为了进行比较,如果您试图获取日期和时间,来自java.time
的现代DateTimeFormatter
将始终引发异常,而不仅仅是13:00之后的时间。我认为这更有帮助。你是对的,我想到的是公共日期解析(字符串文本,ParsePosition pos)
,它在出错时返回null
。