deki08 deki08 - 1 month ago 8
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.setTime(causedAt);
c.add(Calendar.DATE, 1);
if (c.getTime().compareTo(today) < 0) { // It's more than 1 day.
setOneDayOverdue(true);
setFiveDaysOverdue(false);
}


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

So I got following code that works for me:

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

    Calendar causedAt = Calendar.getInstance();
    causedAt.setTime(causedAtDate);

    Calendar yesterday2300 = Calendar.getInstance();
    yesterday2300.setTime(today);
    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.setTime(yesterday2300.getTime());      
    fiveDaysBack2300.add(Calendar.DATE, -4);

    if (causedAt.compareTo(fiveDaysBack2300)<=0) {
        setFiveDaysOverdue(true);
    }
    else if (causedAt.compareTo(yesterday2300)<=0 && causedAt.compareTo(fiveDaysBack2300)>0) {
        setOneDayOverdue(true);
    }
}