use*_*874 15 java datetime compare
我有两个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();
}
Run Code Online (Sandbox Code Playgroud)
现在我想比较上述两个日期和时间.我应该如何在Java中进行比较.
谢谢
fge*_*fge 34
自从Date实现以来Comparable<Date>,它就像:
date1.compareTo(date2);
Run Code Online (Sandbox Code Playgroud)
如Comparable合同规定的那样,如果date1被认为小于/大于/大于/大于date2(在这种情况下,之前/相同/之后),它将返回负整数/零/正整数.
请注意,Date还有.after()和.before()将返回布尔值的方法.
返回值
如果参数 Date 等于此 Date,则为 0;如果此日期在 Date 参数之前,则为小于 0 的值;如果此日期位于 Date 参数之后,则返回一个大于 0 的值。
喜欢
if(date1.compareTo(date2)>0)
Run Code Online (Sandbox Code Playgroud)
小智 5
另一种选择是......
将两个日期转换为毫秒,如下所示
Date d = new Date();
long l = d.getTime();
Run Code Online (Sandbox Code Playgroud)
现在比较两个长值
| 归档时间: |
|
| 查看次数: |
90659 次 |
| 最近记录: |