HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Comparing dates (without the time part) in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withoutthecomparingdatesparttimejava

Problem

In my current project, I have to deal a lot with dates, especially checking if the date entered by user is today, or max one year from today etc. As I find the datetime API of Java7 (which I regrettably still have to use) pretty confusing, in order to keep my code clean and readable, I wrote the following method:

public static int compareDates(Date date1, Date date2) {
    SimpleDateFormat math = new SimpleDateFormat("yyyyMMdd"); // I'm working with servlets, so keeping it thread-safe
    Long date1asLong = new Long(math.format(date1));
    Long date2asLong = new Long(math.format(date2));
    return date1asLong.compareTo(date2asLong);
}

// usage, e.g. to find if the date entered by user is greater than today
if (MyDateUtils.compareDates(dateFromUser, new Date()) > 0) {
    // do the work
} else {
    // scream
}


Anyway, I am not sure whether this approach has any serious drawbacks, so I am throwing it here for review. Looking forward to your comments.

Solution

It's an interesting, simple approach.

But you don't need new Long objects. Better use primitive types instead.

In fact, as @njzk2 pointed out in a comment,
you don't need long at all, as dates in yyyyMMdd format are alphabetically sorted, you can use simple String comparison.

It's good you mention in comments that you create a SimpleDateFormat instance inside the method for thread safety.
Another common solution in such situations is to use a ThreadLocal.
You can wrap a SimpleDateFormat instance in a ThreadLocal so that all threads will have their own copy, eliminating thread safety issues.

Last but not least, "math" is a poor name for a date formatter object.

Putting my suggestions together:

private static final ThreadLocal dateFormatThreadLocal = new ThreadLocal() {
    @Override
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyyMMdd");
    }
};

public static int compareDates(Date date1, Date date2) {
    DateFormat dateFormat = dateFormatThreadLocal.get();
    return dateFormat.format(date1).compareTo(dateFormat.format(date2));
}

Code Snippets

private static final ThreadLocal<DateFormat> dateFormatThreadLocal = new ThreadLocal<DateFormat>() {
    @Override
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyyMMdd");
    }
};

public static int compareDates(Date date1, Date date2) {
    DateFormat dateFormat = dateFormatThreadLocal.get();
    return dateFormat.format(date1).compareTo(dateFormat.format(date2));
}

Context

StackExchange Code Review Q#116108, answer score: 8

Revisions (0)

No revisions yet.