CodePrimate CodePrimate - 1 month ago 3x
Android Question

In Java, How to check if time is within two Date objects

I am trying to create a method in Java that returns true if the current time of day is between a set interval (startTime and endTime).

The date is irrelevant. What is the best way to do this?

Here is my attempt it doesn't work:

public boolean isNowBetweenDateTime()
final Date now = new Date();
return now.after(startTime) && now.before(endTime);

What is the best way (in java) to check if time is within two Date objects, ignoring year, month day?


First of all, I would recommend to use Calendar instead of Date. I had some problems before, using date. And I would use the time in milliseconds to compare dates, this is the safest way. The code wuoul be sth like:

Date now = new Date();

long startTimeInMillis = startTime.getTime();
long endTimeInMillis = endTime.getTime();
return now.getTime >= startTimeInMillis && now.getTime < endTimeInMillis;