java 使用 Joda,如何确定给定日期是否在时间 x 和比 x 早 3 小时的时间之间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4674852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Joda, How do I determine if a given date is between time x and a time 3 hours earlier than x?
提问by Alex B
What is the simplest way to use Joda time and get something like the following behavior:
使用 Joda 时间并获得类似以下行为的最简单方法是什么:
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.
因此,如果someTime
设置为 15:00 并checkTime
设置为 12:15,它应该返回 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
.
如果someTime
设置为 15:00 并checkTime
设置为 11:45 它应该返回 false 因为checkTime
是 3 个多小时之前someTime
。
If someTime
is set to 15:00 and checkTime
is set to 15:15 it should return false because checkTime
is after someTime
.
如果someTime
设置为 15:00 并checkTime
设置为 15:15 它应该返回 false 因为checkTime
是 after someTime
。
回答by Alex B
After some playing around, I found this which reads nicely:
经过一番玩耍后,我发现这个读起来很好:
return new Interval( someTime.minusHours( 3 ), someTime ).contains( checkTime );
回答by Jon Skeet
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.
我用过compareTo
因为没有isBeforeOrEqual
或isAfterOrEqual
- 但你可以compareTo
用于任何关系。
I suspect it was just minusHours
that you were after though :)
我怀疑这只是minusHours
你在追求:)