Compare date without time [duplicate]

2019-02-06 10:04发布

Possible Duplicate:
How to compare two Dates without the time portion?

How to compare date without time in java ?

Date currentDate = new Date();// get current date           
Date eventDate = tempAppointments.get(i).mStartDate;
int dateMargin = currentDate.compareTo(eventDate); 

this code compares time and date !

标签: java time
4条回答
虎瘦雄心在
2楼-- · 2019-02-06 10:48

Write your own method which does not take the time into account:

public static int compareDate(Date date1, Date date2) {
    if (date1.getYear() == date2.getYear() &&
        date1.getMonth() == date2.getMonth() &&
        date1.getDate() == date2.getDate()) {
      return 0 ;
    } 
    else if (date1.getYear() < date1.getYear() ||
             (date1.getYear() == date2.getYear() &&
              date1.getMonth() < date2.getMonth()) ||
             (date1.getYear() == date2.getYear() &&
              date1.getMonth() == date2.getMonth() &&
              date1.getDate() < date2.getDate()) {
      return -1 ;
   }
   else {
     return 1 ;
   }
}

Note that methods getYear(), getMonth() and getDate() have been deprecated. You should go through the Calendar class and perform the same method.

查看更多
姐就是有狂的资本
3楼-- · 2019-02-06 10:49

You can write a method Date withoutTime(Date) that returns a copy of the date in which all time fields (hour, minute, second, milli) are set to zero. Then you can compare these.

Or you can switch to Joda Time if possible. That library already has the data type DateMidnight, which is what you are looking for.

查看更多
ら.Afraid
5楼-- · 2019-02-06 10:55

Try compare dates changing to 00:00:00 its time (as this function do):

public static Date getZeroTimeDate(Date fecha) {
    Date res = fecha;
    Calendar calendar = Calendar.getInstance();

    calendar.setTime( fecha );
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    res = calendar.getTime();

    return res;
}

Date currentDate = new Date();// get current date           
Date eventDate = tempAppointments.get(i).mStartDate;
int dateMargin = getZeroTimeDate(currentDate).compareTo(getZeroTimeDate(eventDate));
查看更多
登录 后发表回答