user1950349 user1950349 - 1 year ago 67
Java Question

How to check whether a time is between particular range?

I need to check whether current time is between 8 AM and 3 PM or not. If it is between those time range, then I need to return yes otherwise return false.

boolean isNowBetweenDateTime(final Date s, final Date e) {
final Date now = new Date();
return now.after(s) && now.before(e);

But I am not sure I should be using
here? Can I just not use timestamp and check timestamp accordingly? What is the right way to do this?

I am still on Java 7.

Answer Source

If you're using a version of Java prior to Java 8, take a look at the API documentation for Joda.

Specifically, there is an AbstractInterval#containsNow() method which will allow you to do what you want.

For example:

new Interval(start, end).containsNow();

where start and end can either be any of a number of different values/objects. See the documentation for the different constructors available: Interval

You could modify your method to be like so:

boolean isNowBetweenDateTime(final DateTime s, final DateTime e) {
    return new Interval(s, e).containsNow();

That said, it's only one line, so you really shouldn't need to wrap it with your own method :)

Again, take a look at the documentation. The Interval constructor can take a variety of objects/values, so pick whichever suits your needs. I recommend DateTime since it seems to best describe what you're looking to do.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download