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 reada, I wrote the folowing 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 does not havy some serious drawbacks, so I am throwing it here for review. Looking forward to your comments.