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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:28:03  来源:igfitidea点击:

Using Joda, How do I determine if a given date is between time x and a time 3 hours earlier than x?

javajodatime

提问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 someTimeis set to 15:00 and checkTimeis set to 12:15 it should return true.

因此,如果someTime设置为 15:00 并checkTime设置为 12:15,它应该返回 true。

If someTimeis set to 15:00 and checkTimeis set to 11:45 it should return false because checkTimeis more than 3 hours before someTime.

如果someTime设置为 15:00 并checkTime设置为 11:45 它应该返回 false 因为checkTime是 3 个多小时之前someTime

If someTimeis set to 15:00 and checkTimeis set to 15:15 it should return false because checkTimeis 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 compareToas there's no isBeforeOrEqualor isAfterOrEqual- but you can use compareTofor any relation.

我用过compareTo因为没有isBeforeOrEqualisAfterOrEqual- 但你可以compareTo用于任何关系。

I suspect it was just minusHoursthat you were after though :)

我怀疑这只是minusHours你在追求:)