简体   繁体   English

如何检查joda时间是否现在正在发生?

[英]How can I check if a joda time instant is taking place now?

I have a list of Instants, I want to iterate though all of them and figure out if any of them are occurring right now. 我有一个即时列表,我想遍历所有实例并找出它们是否正在发生。 Is that possible to do with Instants or did I confuse myself? 这可能与Instants有关,还是我感到困惑?

Was I was supposed to use two dateTime's one for beginning of event and one for after and check that way? 我是否应该将两个dateTime用作事件开始,然后将一个dateTime用于事件并进行检查?

Assuming you mean the class org.joda.time.DateTime when speaking about "Instant" you have to notice that the answer depends on granularity needed for your purpose. 假设您在讲“即时”时指的是org.joda.time.DateTime类, org.joda.time.DateTime您必须注意答案取决于您所需的粒度。 Normally an instant in JodaTime is fine granular down to milliseconds. 通常,在JodaTime中的瞬间可以精确到毫秒。 If you want to compare any instant with "now", meaning DateTime.now() , then I recommend to use an interval instead like following: 如果您想将任何时刻与“ now”(即DateTime.now() ,那么我建议使用一个间隔来代替,如下所示:

DateTime now = DateTime.now();
DateTime from = now.minusMinutes(1); // example - maybe you need seconds instead
DateTime to = now.plusMinutes(1); // example - maybe you need seconds instead
Interval range = new Interval(from, to);

for (DateTime test : instants) { // supposing instants as List<DateTime>
  if (range.contains(test)) {
    return test;
  }
}

// here not found any equality, process according to your needs

Bare in mind that if you use equals() instead then you will hardly hit any instant you might have in your list. 记住,如果使用equals(),则几乎不会遇到列表中的任何瞬间。 And furthermore, the method equals(Object) compares absolute time AND chronology (including time zones). 而且, equals(Object)方法比较绝对时间和年代(包括时区)。 The alternative isEqual(ReadableInstant) only compares the absolute times which is probably better, but due to granularity issues also not ideal. 替代方法isEqual(ReadableInstant)仅比较绝对时间,这可能更好,但是由于粒度问题,也不理想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM