我有两个具有以下格式的 Date
对象。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String matchDateTime = sdf.parse("2014-01-16T10:25:00");
Date matchDateTime = null;
try {
matchDateTime = sdf.parse(newMatchDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get the current date
Date currenthDateTime = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date dt = new Date();
String currentDateTimeString = dateFormat.format(dt);
Log.v("CCCCCurrent DDDate String is:", "" + currentDateTimeString);
try {
currenthDateTime = sdf.parse(currentDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
现在,我想将上述两个日期与时间进行比较。
我应该如何在Java中进行比较。
谢谢
最佳答案
由于Date
实现Comparable<Date>
,所以很容易:
date1.compareTo(date2);
按照
Comparable
契约(Contract)的规定,如果date1
分别被认为小于date2
(小于/等于)或大于Date
(在这种情况下,则在之前/之前/之后),则它将返回负整数/零/正整数。请注意,
.after()
也具有.before()
和ojit_code方法,这些方法将返回 boolean 值。