Most efficient way of checking if Date object and Calendar object are in the same month

Posted by Indigenuity on Stack Overflow See other posts from Stack Overflow or by Indigenuity
Published on 2012-11-07T22:56:01Z Indexed on 2012/11/07 22:59 UTC
Read the original article Hit count: 149

Filed under:
|
|
|
|

I am working on a project that will run many thousands of comparisons between dates to see if they are in the same month, and I am wondering what the most efficient way of doing it would be.

This isn't exactly what my code looks like, but here's the gist:

List<Date> dates = getABunchOfDates();
Calendar month = Calendar.getInstance();
for(int i = 0; i < numMonths; i++) 
{
    for(Date date : dates)
    {
        if(sameMonth(month, date)
            .. doSomething
    }
    month.add(Calendar.MONTH, -1);
}

Creating a new Calendar object for every date seems like a pretty hefty overhead when this comparison will happen thousands of times, soI kind of want to cheat a bit and use the deprecated method Date.getMonth() and Date.getYear()

public static boolean sameMonth(Calendar month, Date date)
{
    return month.get(Calendar.YEAR) == date.getYear() && month.get(Calendar.MONTH) == date.getMonth();
}

I'm pretty close to just using this method, since it seems to be the fastest, but is there a faster way? And is this a foolish way, since the Date methods are deprecated? Note: This project will always run with Java 7

© Stack Overflow or respective owner

Related posts about java

Related posts about Performance