在Java中比较两个日期 [英] Compare two dates in Java
本文介绍了在Java中比较两个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在java中比较两个日期。我使用的代码如下:
I need to compare two dates in java. I am using the code like this:
Date questionDate = question.getStartDate();
Date today = new Date();
if(today.equals(questionDate)){
System.out.println("Both are equals");
}
这不工作。变量的内容如下:
This is not working. The content of the variables is the following:
-
questionDate
包含2010-06-30 00:31:40.0
-
今天
包含Wed Jun 30 01:41:25 IST 2010
questionDate
contains2010-06-30 00:31:40.0
today
containsWed Jun 30 01:41:25 IST 2010
我该如何解决? >
How can I resolve this?
推荐答案
日期相等性取决于两个日期等于毫秒。使用 new Date()
创建新的Date对象永远不会等于过去创建的日期。 Joda时间的API简化了日期工作;但是,仅使用Java的SDK:
Date equality depends on the two dates being equal to the millisecond. Creating a new Date object using new Date()
will never equal a date created in the past. Joda Time's APIs simplify working with dates; however, using the Java's SDK alone:
if (removeTime(questionDate).equals(removeTime(today))
...
public Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
这篇关于在Java中比较两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文