简体   繁体   中英

How to compare item of set collection to current Date?

I have the following set and need to compare its date instance with the current date. Although both dates are the same but the comparison returns false !!

MyClass.java

import java.util.Date;
public class MyClass {
   private Date date;

   ...

}

My Code

 ....
 Set <MyClass> myclass = new HashSet();

 I populate it with some data here...

 for(MyClass m : myclass)
 {
   System.err.println("date>>:" + trim(m.getDate()));  //returns 2013-08-08
   System.err.println("date>>:" + trim(getCurrentDate()));  //returns 2013-08-08
   System.err.println("boolean:" +                            
               trim(m.getDate()).equals(trim(getCurrentDate()))); //returns false
 }
}

 public Date getCurrentDate() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    dateFormat.format(date));
    return date;
}

public Date trim(Date date){
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.HOUR, 0);
    return calendar.getTime();
}

The Date class includes the time of the day to millisecond precision, and the time counts when comparing for equality.

To compare only the "date" part you can do one of several things, for example format the dates as year-month-day and compare the resulting strings, or create Calendar objects from the dates and compare the year, month and day individually. Another option is to make sure the Dates you compare have the same hour of the day, for example 12:00, that way you can use the equals method.

Each time you call getCurrentDate , you might receive a new date. Formatting it the way you do is essentially a no-op and the date still carries its hours, minutes, seconds and milliseconds.

So they are actually proably different for real.

You could remove this extra information to get the desired behaviour.

Dates are not same, they may differ by millis/sec. Date equals doesn't depend upon format of date but compares value. Below code would return false as well:

Date d1 = new Date();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
        Date d2 = new Date();
        f.format(d2);
        System.out.println(d1);//e.g. Thu Aug 08 12:09:24 IST 2013
        System.out.println(d2);//e.g. Thu Aug 08 12:09:26 IST 2013
        System.out.println(d1.equals(d2));//false

Date.equals compares time ( Date.getTime() ), equals will return true only if they matches:

public boolean equals(Object obj) {
        return obj instanceof Date && getTime() == ((Date) obj).getTime();
    }

Per javadoc:

 The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object. 

Thus, two Date objects are equal if and only if the getTime method returns the same long value for both. 

Date.getTime return the number of milliseconds since January 1, 1970, 00:00:00 GMT

So in you updated question with trim , consider you are comparing two long values of time in millis.

If you require to compare yyyy-MM-dd values of two different date instances, consider using String.equals instead (hack way):

SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String date1 = f.format(new Date());//2013-08-08
        String date2 = f.format(new Date());//2013-08-08
        System.out.println(date1.equals(date2));

You can use GregorianCalendar and Calendar#get(..) to only compare year, month, and day.
There is a perfect sample from the javadoc :

 // get the supported ids for GMT-08:00 (Pacific Standard Time)
 String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
 // if no ids were returned, something is wrong. get out.
 if (ids.length == 0)
     System.exit(0);

  // begin output
 System.out.println("Current Time");

 // create a Pacific Standard Time time zone
 SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);

 // set up rules for Daylight Saving Time
 pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
 pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);

 // create a GregorianCalendar with the Pacific Daylight time zone
 // and the current date and time
 Calendar calendar = new GregorianCalendar(pdt);
 Date trialTime = new Date();
 calendar.setTime(trialTime);

 // print out a bunch of interesting things
 System.out.println("ERA: " + calendar.get(Calendar.ERA));
 System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
 System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
 System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
 System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
 System.out.println("DATE: " + calendar.get(Calendar.DATE));
 System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
 System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
 System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
 System.out.println("DAY_OF_WEEK_IN_MONTH: "
                    + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
 System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
 System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
 System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
 System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
 System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
 System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
 System.out.println("ZONE_OFFSET: "
                    + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000)));
 System.out.println("DST_OFFSET: "
                    + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000)));

Actually there is a problem in your method..

 public Date getCurrentDate() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    dateFormat.format(date);
    return date;
}

dateFormat.format(date) will return a String date in yyyy-MM-dd format but you are returning date from this method which will return the Date in 'Thu Aug 08 12:21:34 IST 2013' this format not in '2013-08-08' this. So you should take the String as return from this method and then compare it by equals. Try this, I think this should help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM