deki08 deki08 - 1 year ago 77
Java Question

How can I check if date is before a specific time?

I have to check, if a date variable is before a specific time. The variable has the format dd.MM.yyyy HH:mm:ss.

Let's take todays date 31.10.2016 15:20:45. The value of the variable is 30.10.2016 14:00:21. How can I check now if the variable is one day older than today and if the time is before or equals 23:00?

I tried following code.

Date today = new Date();
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1);
if (c.getTime().compareTo(today) < 0) { // It's more than 1 day.

But with this code the part with the time is missing.

The solution should work with Java 7 and without any external libraries like Joda-Time.

Answer Source

So I got following code that works for me:

public void setOverdueFlagIfRequired(Date today, Date causedAtDate) {       
    Calendar now = Calendar.getInstance();

    Calendar causedAt = Calendar.getInstance();

    Calendar yesterday2300 = Calendar.getInstance();
    yesterday2300.add(Calendar.DATE, -1);
    yesterday2300.set(Calendar.HOUR_OF_DAY, 23);
    yesterday2300.set(Calendar.MINUTE, 0);
    yesterday2300.set(Calendar.SECOND, 0);
    yesterday2300.set(Calendar.MILLISECOND, 0);

    Calendar fiveDaysBack2300 = Calendar.getInstance();
    fiveDaysBack2300.add(Calendar.DATE, -4);

    if (causedAt.compareTo(fiveDaysBack2300)<=0) {
    else if (causedAt.compareTo(yesterday2300)<=0 && causedAt.compareTo(fiveDaysBack2300)>0) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download