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).
This creates a date in the future and compares it with the current date (set to late evening). You should consider using the Joda Time Library.
long timeStampOfTomorrow = new Date().getTime() + 86400000L;
Date dateToCheck = new Date(timeStampOfTomorrow);
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 23);
today.set(Calendar.MINUTE, 59);
today.set(Calendar.SECOND, 59);
today.set(Calendar.MILLISECOND, 999);
boolean isExpired = dateToCheck.after(today.getTime());
With Joda Time Library you could do this more readable. An easy example can be found on the project website.
public boolean isRentalOverdue(DateTime datetimeRented) {
Period rentalPeriod = new Period().withDays(2).withHours(12);
return datetimeRented.plus(rentalPeriod).isBeforeNow();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With