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

Categories

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

java - Comparing two Calendar objects

I want to compare two Calendar objects to see if they both contain the same date. I don't care about any value below days.

I've implemented this and I can't think about any case where it should fail:

private static boolean areEqualDays(Calendar c1, Calendar c2) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    return (sdf.format(c1.getTime()).equals(sdf.format(c2.getTime())));
}

Is this approach correct or should I compare c1 and c2 field by field?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Try compareTo

Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.compareTo(c2);

Returns:

the value 0 if the time represented by the argument is equal to the time represented by this Calendar; a value less than 0 if the time of this Calendar is before the time represented by the argument; and a value greater than 0 if the time of this Calendar is after the time represented by the argument.

EDIT

import org.apache.commons.lang3.time.DateUtils;

You can use DateUtils.isSameDay to check if it's the same day.

boolean isSameDay = DateUtils.isSameDay(c1, c2);

28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true. 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...