newbie newbie - 1 month ago 6
Java Question

Expiring date today in Java

I need to check if given date is after today 23:59:59, how can I create date object that is today 23:59:59?


Use java.util.Calendar:

Calendar cal = Calendar.getInstance(); // represents right now, i.e. today's date
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999); // credit to f1sh

Date date = cal.getTime();

I think you might be approaching this from slightly the wrong angle, though. Instead of trying to create a Date instance that's one atom before midnight, a better approach might be to create the Date that represents midnight and testing whether the current time is strictly less than it. I believe this would be slightly clearer in terms of your intentions to someone else reading the code too.

Alternatively, you could use a third-party Date API that knows how to convert back to date. Java's built-in date API is generally considered to be deficient in many ways. I wouldn't recommend using another library just to do this, but if you have to do lots of date manipulation and/or are already using a library like Joda Time you could express this concept more simply. For example, Joda Time has a DateMidnight class that allows much easier comparison against "raw" dates of the type you're doing, without the possibility for subtle problems (like not setting the milliseconds in my first cut).