如何在java中比较两个日期和时间 [英] How to compare two dates along with time in java

查看:283
本文介绍了如何在java中比较两个日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有以下格式的Date对象。

I have two Date objects with the below format.

    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中比较。

Now I want to compare the above two dates along with time. How should I compare in Java.

谢谢

推荐答案

p>由于 Date implements Comparable< Date> ,它很容易:

Since Date implements Comparable<Date>, it is as easy as:

date1.compareTo(date2);

由于 Comparable 合约规定,返回一个负整数/零/正整数,如果 date1 分别被认为小于/大于 date2

As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).

注意 Date 也有 .after() .before()将返回布尔值。

Note that Date has also .after() and .before() methods which will return booleans instead.

这篇关于如何在java中比较两个日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆