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).
Use the Date.before(Date) or Date.after(Date)
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MINUTE, 59);
Date d = c.getTime()
Date x = // other date from somewhere
x.after(d);
Find the tomorrow date convert it into millisecond you get a long value. subtract -1 from it and again convert to date you will get your required date.
ex : 12:00:00 of tomorrow convert it into milliseconds. you will get like a long value 312313564774 subtract -1 you will get today eod time in milliseconds
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();
}