如何检查Java中是否已经过了X秒?

Ale*_*nor 3 .net c# java time datetime

我在.NET中知道我可以这样做:

DateTime test = DateTime.Now;
if (test >= (pastTime + TimeSpan.FromSeconds(15)) {
    doSomething();
}
Run Code Online (Sandbox Code Playgroud)

什么是Java等价物?

f1s*_*1sh 12

对于这个简单的检查,我建议只使用时间戳(以毫秒为单位),而不是使用java.util.Date或其他一些类:

long test = System.currentTimeMillis();
if(test >= (pastTime + 15*1000)) { //multiply by 1000 to get milliseconds
  doSomething();
}
Run Code Online (Sandbox Code Playgroud)

请注意,pastTime变量也必须以毫秒为单位.

不幸的是,没有合适的"内置"java类来处理时间跨度.为此,请查看Joda Time库.


Jas*_*ski 5

从 JDK8 开始的 java 时间库可以执行以下操作:

import java.time.Duration
import java.time.Instant

class MyTimeClass {
    
    public static void main(String[] args) {
        Instant then = Instant.now();
        Duration threshold = Duration.ofSeconds(3);
        // allow 5 seconds to pass
        Thread.sleep(5000);        
        assert timeHasElapsedSince(then, threshold) == true;
    }

    public static boolean timeHasElapsedSince(Instant then, Duration threshold) {
        return Duration.between(then, Instant.now()).toSeconds() > threshold.toSeconds();
    }
}
Run Code Online (Sandbox Code Playgroud)