How to check whether a time is between particular

2019-02-27 12:28发布

问题:

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 Date 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.

回答1:

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.



回答2:

Joda Time is a pretty straightforward library to be used, and if you define the comparison date objects as LocalDate, then you can use the isBefore(), isAfter() boolean methods: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#isBefore-java.time.chrono.ChronoLocalDateTime- Hope it helps!



回答3:

java.time

You are using old outmoded classes. They have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

LocalTime

The LocalTime class actually truly represents a time-of-day only value, unlike the old java.sql.Time and java.util.Date classes.

LocalTime start = LocalTime.of( 8 , 0 );
LocalTime stop = LocalTime.of( 15 , 0 );

Time zone

Determining the current time requires a time zone. For any given moment the time varies around the globe by time zone.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalTime now = LocalTime.now( zoneId );

Compare

Compare by calling equals, isAfter, or isBefore. We use the Half-open approach here as is common in date-time work where the beginning is inclusive while the ending is exclusive.

 Boolean isNowInRange = ( ! now.isBefore( start ) ) && now.isBefore( stop ) ;


回答4:

Using Date for the current time is fine. There's a few ways you can go about it.

1. System.currentTimeInMillis()

2. Date today = new Date()