Using Joda, How do I determine if a given date is between time x and a time 3 hours earlier than x?
What is the simplest way to use Joda time and ge开发者_Python百科t something like the following behavior:
public boolean check( DateTime checkTime )
{
DateTime someTime = new DateTime(); //set to "now" for sake of example
return checkTime.isBefore( someTime ) && checkTime.notMoreThanThreeHoursBefore( someTime );
}
So if someTime
is set to 15:00 and checkTime
is set to 12:15 it should return true.
If someTime
is set to 15:00 and checkTime
is set to 11:45 it should return false because checkTime
is more than 3 hours before someTime
.
If someTime
is set to 15:00 and checkTime
is set to 15:15 it should return false because checkTime
is after someTime
.
After some playing around, I found this which reads nicely:
return new Interval( someTime.minusHours( 3 ), someTime ).contains( checkTime );
Easy:
DateTime someTime = new DateTime();
DateTime earliest = someTime.minusHours(3);
if (earliest.compareTo(checkTime) <= 0 && checkTime.compareTo(someTime) < 0)
I've used compareTo
as there's no isBeforeOrEqual
or isAfterOrEqual
- but you can use compareTo
for any relation.
I suspect it was just minusHours
that you were after though :)
精彩评论