Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

datetime - How to compare two dates along with time in java

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();
}

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

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

date1.compareTo(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).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...